[英]get index of matched element between two array of objects in javascript
我有两个对象数组。 我想从数组 2 中获取匹配元素的索引。如何找到它?
这是一个例子。
数组 1
selectedProduct: [{id:2, name:"product 1", category:"home"}]
阵列 2
allProducts: [{id:1, name:"product 3", category:"grocery"},
{id:2, name:"product 1", category:"home"},{id:3, name:"product 4",category:"vegetables"}]
代码片段:
const index = this.allProducts.findIndex(item => this.selectedproduct.filter(entry => entry.id === item.id))
但是,它返回 0。我怎样才能得到匹配元素的索引?
改用some
:
let selectedProduct = [ {id:2, name:"product 1", category:"home"} ]; let allProducts = [ {id:1, name:"product 3", category:"grocery"}, {id:2, name:"product 1", category:"home"}, {id:3, name:"product 4",category:"vegetables"} ] const index = allProducts.findIndex(item => selectedProduct.some(entry => entry.id === item.id)); console.log(index);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.