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...

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e9349b-1444.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e9349b-1444.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?