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