[英]Find and Return an object from an array of array of objects using a property value
I have an array of array of objects.我有一组对象数组。 Is there an ES6 way to find and return an object based on a property value?
是否有 ES6 方法可以根据属性值查找并返回 object?
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.给定“apple”的值属性名称,我希望返回 object
{ name: 'apple', y: 1}
。
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.我试过
tempArray.filter(k => k.some(e => e.name === 'apple'))
但它返回一个我不想要的对象数组。
Thanks for your help in advance,提前感谢您的帮助,
Flatten the array, then use .find
to find the matching object:将数组展平,然后使用
.find
找到匹配的 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.