I have a case where I have Array of Arrays and each inner array has multiple objects as below:
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' }
]
];
I want to pull out the array which contains the object whose property id
is matching with any particular number, say 896
With ES6 I tried this
rawList = arrayOfArraysOfObjects.filter(obj => Object.keys(obj).reduce((acc, curr) => acc || obj[curr] === my.id, false));
return rawList;
here my.id is 896
but this didn't work, MY EXPECTED OUTPUT:
[
{ name: 'abv', id: '1012' },
{ name: 'gfgf', id: '881' },
{ name: 'John', id: '896' }
]
hence, tried correcting it as:
rawList = arrayOfArraysOfObjects.map((apprGrp) => {
const filteredList = apprGrp.filter(obj => Object.keys(obj).reduce((acc, curr) => acc || obj[curr] === my.id, false));
return filteredList;
});
this also didnt gave me the above metioned desired result. Please suggest how can I correct this to get the desired results
You can simply use a array filter and a find to filter by the item
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());