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