问题描述
我有这个带有一些值的对象;其中有一个 byKey
对象和一些其他对象:
const myObject = {
byKey: {
1: {
id: "One",getIt: true,},2: {
id: "Two",getIt: false,3: {
id: "Three",4: {
id: "Four",someOtherValue1: true,someOtherValue2: false,};
我想得到一个新对象,用 byKey
删除所有 getIt: false
对象,所以我得到:
const myResultObject = {
byKey: {
1: {
id: "One",};
我是这样做的:
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",// },// someOtherValue1: true,// someOtherValue2: false,// };
效果很好,但有点冗长,有时阅读起来会很复杂。 有没有更好的方法?
解决方法
实现目标的一种方法是使用 Object.fromEntries()
和 Object.entries()
。对条目使用 .filter()
,您可以删除值的 [key,value]
为 getIt
的 false
元素。过滤条目以删除不需要的键值对后,您可以通过 Object.fromEntries()
const myObject = { byKey: { 1: { id: "One",getIt: true,},2: { id: "Two",getIt: false,3: { id: "Three",4: { id: "Four",someOtherValue1: true,someOtherValue2: false,};
const res = {
...myObject,byKey: Object.fromEntries(
Object.entries(myObject.byKey).filter(([,{getIt}]) => getIt)
)
}
console.log(res);
为了更好的可读性,你可以这样做,
let myObject = {
byKey: {
1: {
id: "One",2: {
id: "Two",3: {
id: "Three",4: {
id: "Four",};
let { byKey } = myObject;
let newByKey = {};
Object.keys(byKey).forEach(key => {
if(byKey[key].getIt) {
newByKey[[key]] = byKey[key];
}
})
myObject = {...myObject,byKey: newByKey};
console.log(myObject);