繁体   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