Curcuma_
Curcuma_

Reputation: 901

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.

Upvotes: 0

Views: 61

Answers (2)

Moti Korets
Moti Korets

Reputation: 3748

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

Upvotes: 4

Sebastian Speitel
Sebastian Speitel

Reputation: 7336

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);

Upvotes: 5

Related Questions