There is a group object, how to get the object of the object in the array through a key value (id=1)?

for example, an array of objects:

let people = [{id: 1, name: "Bob"}, {id: 2, name: "Alice"}, {id: 3, name: "Lilei"}]

how can I easily get the {id: 1, name: "Bob"} object through a known id=1 ?
except for methods that traverse directly.

Jul.05,2022

use es6's find:

let r = people.find(v => v.id === 1)

  function searchById(id) {
    let people = [{id: 1, name: 'Bob'}, {id: 2, name: 'Alice'}, {id: 3, name: 'Lilei'}]
    return new Map(people.map(item=>[item.id, item])).get(id)
  }
  searchById(1)

if the word string is not traversed, use regular


can be obtained directly through the subscript

let people = [{id: 1, name: 'Bob'}, {id: 2, name: 'Alice'}, {id: 3, name: 'Lilei'}];
let id = 1;
let obj = people[id - 1];
console.log(obj)

Uh. Misunderstand the meaning of the topic, please ignore it.


array.filter: http://www.runoob.com/jsref/j...

Menu