Reputation: 901
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:
Upvotes: 0
Views: 61
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
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