0

我有一个案例,我有数组数组,每个内部数组都有多个对象,如下所示:

const arrayOfArraysOfObjects = [
  [
    { name: 'abv', id: '1212' },
    { name: 'gfgf', id: '887' },
    { name: 'John', id: '886' }
  ],
  [
    { name: 'abv', id: '1242' },
    { name: 'gfgf', id: '837' },
    { name: 'John', id: '816' }
  ],
  [
    { name: 'abv', id: '1242' },
    { name: 'gfgf', id: '837' },
    { name: 'John', id: '896' }
  ]
];

我想拉出包含其属性id与任何特定数字匹配的对象的数组,比如 896

使用 ES6 我试过这个

rawList = arrayOfArraysOfObjects.filter(obj => Object.keys(obj).reduce((acc, curr) => acc || obj[curr] === my.id, false));
return rawList;

这里 my.id 是 896

但这不起作用,我的预期输出:

[
   { name: 'abv', id: '1012' },
   { name: 'gfgf', id: '881' },
   { name: 'John', id: '896' }
]

因此,尝试将其更正为:

rawList = arrayOfArraysOfObjects.map((apprGrp) => {
  const filteredList = apprGrp.filter(obj => Object.keys(obj).reduce((acc, curr) => acc || obj[curr] === my.id, false));
  return filteredList;
});

这也没有给我上面提到的预期结果。请建议我如何纠正这个以获得所需的结果

4

3 回答 3

3

您可以简单地使用数组过滤器和 find 按项目过滤

const arrayOfArraysOfObjects = [
  [
   { name: 'abv', id: '1212' },
   { name: 'gfgf', id: '887' },
   { name: 'John', id: '886' }
  ],
  [
   { name: 'abv', id: '1242' },
   { name: 'gfgf', id: '837' },
   { name: 'John', id: '816' }
  ],
  [
   { name: 'abv', id: '1242' },
   { name: 'gfgf', id: '837' },
   { name: 'John', id: '896' }
  ]
];

console.log(arrayOfArraysOfObjects.filter(x => x.find(y => y.id === '896')).flat());

于 2020-11-21T07:18:22.473 回答
1

您可以检查此解决方案。

const data = [
  [
    { name: "abv", id: "1212" },
    { name: "gfgf", id: "887" },
    { name: "John", id: "886" },
  ],
  [
    { name: "abv", id: "1242" },
    { name: "gfgf", id: "837" },
    { name: "John", id: "816" },
  ],
  [
    { name: "abv", id: "1242" },
    { name: "gfgf", id: "837" },
    { name: "John", id: "896" },
  ],
];

const filterData = (id) => data.filter((arr) => arr.some((obj) => obj.id == id));

console.log(filterData(837));

于 2020-11-21T07:20:14.723 回答
1

由于您正在寻找具有所需id用途的单个子数组,Array.find()而不是Array.filter(). 用于Array.some()检查当前子数组是否包含id

const data = [[{"name":"abv","id":"1212"},{"name":"gfgf","id":"887"},{"name":"John","id":"886"}],[{"name":"abv","id":"1242"},{"name":"gfgf","id":"837"},{"name":"John","id":"816"}],[{"name":"abv","id":"1242"},{"name":"gfgf","id":"837"},{"name":"John","id":"896"}]];

const findSubArray = id => data.find(arr => arr.some(o => o.id === id));

console.log(findSubArray('837'));

于 2020-11-21T12:03:53.063 回答