Reputation: 87
I have an array of array of objects. Is there an ES6 way to find and return an object based on a property value?
const tempArray = [];
tempArray.push([{ name: 'apple', y: 1}, { name: 'orange', y: 2}]);
tempArray.push([{ name: 'pear', y: 3}]);
Given the value property name of 'apple', I want the object { name: 'apple', y: 1}
returned.
I've tried tempArray.filter(k => k.some(e => e.name === 'apple'))
but it returns an array of array of objects which I don't want.
Thanks for your help in advance,
Upvotes: 0
Views: 43
Reputation: 371168
Flatten the array, then use .find
to find the matching object:
const tempArray = [];
tempArray.push([{ name: 'apple', y: 1}, { name: 'orange', y: 2}]);
tempArray.push([{ name: 'pear', y: 3}]);
const obj = tempArray.flat().find(({ name }) => name === 'apple');
console.log(obj);
Upvotes: 1