0

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,

1
  • 1
    You do have an array of array of objects. Why not maintain a single level array in the first place? Commented Apr 28, 2020 at 22:29

1 Answer 1

1

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.