简体   繁体   中英

Array of Json indexing in Javascript

Having such an object

obj = [{id:1, val:"blabla"}, {id:2, val:"gnagna"}] 

How can we index obj with id like obj[id==1] (Pandas Pythonic way).

I assume the followings:

  1. Objects inside the array all have ids.
  2. The first appearing id that matches is taken, assuming other objects matching are equal.

You can use find method for that. obj.find( o => o.id == index)

 obj = [{id:1, val:"blabla"}, {id:2, val:"gnagna"}] function getBy(index){ return obj.find( o => o.id == index) } console.log(getBy(1)) console.log(getBy(2)) 

You can use the find() method to find an item on a specific condition, defined in the callback.

The callback in this case would be

function f(i){return i.id === 1}

or using an arrow function:

i => i.id === 1

 var obj = [{ id: 1, val: "blabla" }, { id: 2, val: "gnagna" }] var item = obj.find(i => i.id === 1); console.log(item); 

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