按值过滤由对象组成的对象元素,vanilla JS

Filter elements of object composed by objects by value, vanilla JS

这个对象有一些值;其中有一个 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,
// };

效果很好,但有点冗长,有时读起来会很复杂。 有更好的方法吗?

实现目标的一种方法是在条目上使用 Object.fromEntries() and Object.entries(). Using .filter(),您可以删除值 getIt 为 [=16= 的 [key, value] 元素].过滤条目以删除不需要的键值对后,您可以通过 Object.fromEntries()

将条目转换回对象

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, };

const res = {
  ...myObject,
  byKey: Object.fromEntries(
    Object.entries(myObject.byKey).filter(([, {getIt}]) => getIt)
  )
}
console.log(res);

为了更好的可读性,你可以这样做,

let 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,
};

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);