【发布时间】:2021-04-20 09:47:00
【问题描述】:
我有这个带有一些值的对象;其中有一个 byKey 对象和其他一些对象:
const myObject = {
byKey: {
1: {
id: "One",
getIt: true,
},
2: {
id: "Two",
getIt: false,
},
3: {
id: "Three",
getIt: true,
},
4: {
id: "Four",
getIt: false,
},
},
someOtherValue1: true,
someOtherValue2: false,
};
我想得到一个新对象,用getIt: false 删除所有byKey 对象,所以我得到:
const myResultObject = {
byKey: {
1: {
id: "One",
getIt: true,
},
3: {
id: "Three",
getIt: true,
},
},
someOtherValue1: true,
someOtherValue2: false,
};
我是这样做的:
const myObjectByKeyElementsArray = Object.values(myObject.byKey).filter(
(item) => item.getIt === true
);
const myResultObject = myObjectByKeyElementsArray.reduce(
(acc, curr) => ({
...myObject,
byKey: {
...acc.byKey,
[curr.id]: curr,
},
}),
{}
);
console.log(myResultObject);
// const myResultObject = {
// byKey: {
// 1: {
// id: "One",
// getIt: true,
// },
// 3: {
// id: "Three",
// getIt: true,
// },
// },
// someOtherValue1: true,
// someOtherValue2: false,
// };
效果很好,但有点冗长,有时阅读起来会很复杂。 有更好的方法吗?
【问题讨论】:
标签: javascript object functional-programming reduce