Reputation: 55
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
Upvotes: 0
Views: 87
Reputation: 191976
Since you are looking to find a single sub-array with the required id
use Array.find()
instead of Array.filter()
. Use Array.some()
to check if the current sub-array contains the 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'));
Upvotes: 1
Reputation: 16334
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());
Upvotes: 3
Reputation: 6057
You can check this solution.
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));
Upvotes: 1