簡體   English   中英

無法獲取數組中對象的索引

[英]Unable to get index of an object in array

我以為如果我保留原始參考文獻,我只會得到索引

const selected = {id: "abcd123", quantity: "5"};
const location = [
  {id: "abcd123", quantity: "3"},
  {id: "abcd1234", quantity: "3"},
];
const filterLocation = location.filter(loc => loc.id === selected.id);
console.log(location.indexOf(filterLocation));

我希望它將記錄為0但始終返回-1 實際如何運作?

  const selected = {id: "abcd123", quantity: "5"};
  const location = [
    {id: "abcd123", quantity: "3"},
    {id: "abcd1234", quantity: "3"},
  ];
 const filterLocation = location.filter(loc => loc.id === selected.id);

 console.log(location.findIndex(value => value.id === filterLocation[0].id )));

filter返回一個新數組。 因此,您只需要訪問在此示例中filtered那個值

indexOf更改為findIndex location是一個對象數組,因此您需要再次迭代所有數組以恢復索引。 當然,僅此示例,您也可以在同一filter操作中恢復索引。

 console.log(location.findIndex(value => value.id === filterLocation[0].id )));

首先filterLocation不包含任何與location相同的對象。 它包括唯一具有相同id字段但quantity字段不同的對象。 其次, indexOf方法不適用於非標量參數。

抱歉,是我的錯

我認為我應該切換到findIndex而不是indexOf

const selected = {id: "abcd123", quantity: "5"};
const location = [
 {id: "abcd123", quantity: "3"},
 {id: "abcd1234", quantity: "3"},
];
const filterLocation = location.filter(loc => loc.id === selected.id);
console.log(location.findIndex(loc => loc.id === selected.id));

然后,我將獲得所需的指定索引。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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