【问题标题】:Find array of objects from keys array从键数组中查找对象数组
【发布时间】:2019-07-10 12:54:55
【问题描述】:

我有一个对象数组

let objList = [
 {
  id:10,
  ...
 },

 {
  id: 12,
  ...
 },

 {
  id: 13,
  ...
 },

 ...
];

我想过滤掉所有ID在另一个数组中的对象

let keyList = [10, 13];

Expected output:

[
 {
  id: 10,
  ...
  },

 {
  id: 13,
  ...
 }
]

注意

请求。在 Angular 7 应用程序中,我也使用 Lodash 库。

我试过了:

objList.filter(eachObj => keysList.forEach(
          eachID => {
            eachID == eachObj['id']
          }
        ))

find(ObjList, eachObj => {

          return eachObj['id'] === keysList.map(eachID => {
            return eachID;
          })
        })

【问题讨论】:

  • let result = objList.filter(({id}) => keyList.includes(id))
  • 问题显示没有努力解决问题。始终向我们展示您尝试过的内容和研究过的内容

标签: javascript typescript underscore.js lodash


【解决方案1】:

你可以使用过滤器:

objList = objList.filter(element => keyList.indexOf(element.id) > -1);

【讨论】:

    【解决方案2】:

    您没有得到想要的结果,因为您没有从数组中获得 id 字段。 所以尝试使用includes方法并获取id属性:

    const filteredArray = objList.filter(o => keyList.includes(o.id));
    console.log(filteredArray);
    

    【讨论】:

      【解决方案3】:

      使用_.differenceWith()idkey 进行比较,并删除两个数组中都存在的项:

      const objList = [{ id: 10 }, { id: 12 }, { id: 13 }];
      const keyList = [10, 13];
      
      const result = _.differenceWith(objList, keyList, ({ id }, key) => id === key);
      
      console.log(result);
      <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.13/lodash.js"></script>

      【讨论】:

        猜你喜欢
        • 2023-01-17
        • 1970-01-01
        • 1970-01-01
        • 2021-10-04
        • 2020-07-22
        • 2017-12-24
        • 1970-01-01
        • 1970-01-01
        • 2018-03-04
        相关资源
        最近更新 更多