Javascript ES6-如何通过在Java脚本中过滤返回嵌套对象属性值 基于过滤器查找嵌套对象特性值
请建议识别给定项目id 03的名称的最佳方法Javascript ES6-如何通过在Java脚本中过滤返回嵌套对象属性值 基于过滤器查找嵌套对象特性值,javascript,filter,ecmascript-6,Javascript,Filter,Ecmascript 6,请建议识别给定项目id 03的名称的最佳方法 const product = products.find(product => product.items.some(item => item.id === '03')); 提供产品,但必须再次循环才能找到名称 const products = [ { id: 'p1', items: [ { id: 01, name: 'iphone'
const product = products.find(product => product.items.some(item => item.id === '03'));
提供产品,但必须再次循环才能找到名称
const products = [
{
id: 'p1',
items: [
{
id: 01,
name: 'iphone'
},
{
id: 02,
name: 'samsung'
},
{
id: 03,
name: 'oneplus'
}
]
},
{
id: 'p2',
items: [
{
id: 04,
name: 'nokia'
},
{
id: 05,
name: 'nexus'
},
{
id: 06,
name: 'phone3'
}
]
}
]
}
]
我想:
const product = products
.reduce((acc, product) => {
return [...acc, ...product.items];
}, [])
.find(item => item.id === "03");
const productName = product && product.name;
console.log(productName); // oneplus
因为您似乎关心性能,而且看起来只有一个匹配id—经典的
for
循环最适合此任务
let matchingItem;
for (let i = 0; i < products.length; i++){
const product = products[i];
matchingItem = product.items.find(item => item.id === "03");
if (matchingItem) {
break;
}
}
let匹配项;
for(设i=0;iitem.id==“03”);
如果(匹配项){
打破
}
}
这不是很新奇,但一旦找到匹配项就停止执行的功能使其成为最佳选择。谢谢Arup最后一句话应该是:它应该是const productName=product&&product.name@乔:是的。我失去了互联网,所以我无法纠正我的错误。是的,我同意,但并不是很多人喜欢老式的for循环,因为当发现匹配项时,新版本的ES6函数会中断