简体   繁体   中英

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 . 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. So, you just need access to that value filtered in this example

change indexOf for findIndex . location is an array of objects so you need to iterate all the array again for recover the index. Sure, it's just for this example, also you could recover the index in the same filter operation.

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

First of all the filterLocation does not include any object identical to the location . It includes the only object with the same id field but the quantity field is different. Secondly the indexOf method does not work properly for non-scalar arguments.

Sorry my mistake

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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