簡體   English   中英

獲取javascript中兩個對象數組之間匹配元素的索引

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM