【问题标题】:Filter elements of object composed by objects by value, vanilla JS按值过滤由对象组成的对象的元素,vanilla JS
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      您可以通过使用Object.fromEntries() 和Object.entries() 来实现您所追求的目标。在条目上使用.filter(),您可以删除值getIt 为false 的[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);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-07-24
        • 2020-09-29
        • 2021-11-12
        • 1970-01-01
        • 2021-10-28
        • 1970-01-01
        • 2021-11-03
        相关资源
        最近更新 更多