0

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.
3
  • 2
    Your question lacks precision. Consider editing it by adding context, code, etc ... See How to create a Minimal, Complete, and Verifiable example. Commented Apr 16, 2018 at 8:09
  • 1
    What do you mean with "index it"? Do you want to access the objects (e.g. {id:1, val:"blabla"}) by their id? Commented Apr 16, 2018 at 8:10
  • you do obj[0]->id Commented Apr 16, 2018 at 8:10

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

Comments

4

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

1 Comment

find as there will be only one element.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.