indexOf method in an object array?

前端 未结 27 2472
别跟我提以往
别跟我提以往 2020-11-22 02:18

What\'s the best method to get the index of an array which contains objects?

Imagine this scenario:

var hello = {
    hello: \'world\',
    foo: \'ba         


        
27条回答
  •  囚心锁ツ
    2020-11-22 02:29

    You can simply use

    const someId = 2;
    const array = [{id:1}, {id:2}, {id:3}];
    const index = array.reduce((i, item, index) => item.id === someId ? index : i, -1);
    alert('someId ' + someId + ' is at index ' + index);

    No underscore, no for, just a reduce.

提交回复
热议问题