简体   繁体   English

无法获取数组中对象的索引

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

I thought if I maintain the original reference than I would simply get the index 我以为如果我保留原始参考文献,我只会得到索引

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));

I expect it would log 0 but it always return -1 . 我希望它将记录为0但始终返回-1 How it actually works? 实际如何运作?

  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 return a new array. filter返回一个新数组。 So, you just need access to that value filtered in this example 因此,您只需要访问在此示例中filtered那个值

change indexOf for findIndex . indexOf更改为findIndex location is an array of objects so you need to iterate all the array again for recover the index. location是一个对象数组,因此您需要再次迭代所有数组以恢复索引。 Sure, it's just for this example, also you could recover the index in the same filter operation. 当然,仅此示例,您也可以在同一filter操作中恢复索引。

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

First of all the filterLocation does not include any object identical to the location . 首先filterLocation不包含任何与location相同的对象。 It includes the only object with the same id field but the quantity field is different. 它包括唯一具有相同id字段但quantity字段不同的对象。 Secondly the indexOf method does not work properly for non-scalar arguments. 其次, indexOf方法不适用于非标量参数。

Sorry my mistake 抱歉,是我的错

I think I should switch to findIndex instead of 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));

Then I would get the specified index that I need. 然后,我将获得所需的指定索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM