es6 嵌套数组循环,ES6 - 在嵌套数组中查找数据

In ES6 using find or filter I'm quite comfortable iterating through to find an element in an array using a value.

However, I'm trying to get a value from a parent array based upon a value from a nested array.

For example, in this data structure:

products: [

{

id: 01,

items: [

{

id: 01,

name: 'apple'

},

{

id: 02,

name: 'banana'

},

{

id: 03,

name: 'orange'

}

]

},

{

id: 02,

items: [

{

id: 01,

name: 'carrot'

},

{

id: 02,

name: 'lettuce'

},

{

id: 03,

name: 'peas'

}

]

},

{

id: 03,

items: [

{

id: 01,

name: 'eggs'

},

{

id: 02,

name: 'bread'

},

{

id: 03,

name: 'milk'

}

]

}

]

If I know the name or id of the object milk, is there a way to find out the id of the element it's nested within?

Currently I have this:

products.find((product) => {

product.find((prod) => {

return prod.name === 'milk';

});

});

Which only returns the object containing milk.

解决方案

You have to return something from the callback of the outer find. In fact, for the inner iteration you shouldn't use find but rather some that returns a boolean for whether an element matching the condition exists within the arrray:

products.find((product) => {

return product.items.some((item) => {

//^^^^^^

return item.name === 'milk';

});

});

or in short:

products.find(product => product.items.some(item => item.name === 'milk'));

Then check whether find found something (not null!) and get its .id, the result should be 03. Alternatively, you can filter for the products containing milk as an item and then map all the results to their id:

products.filter(product =>

product.items.some(item => item.name === 'milk');

).map(product =>

product.id

) // [03]

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值