Javascript - getting object id using find

1017 views javascript
-2

I have a nested array, and I know the id of the person (person.id) but am trying to find the id of the object. So effectively the 'parent' id.

{

         {
                "id": "12345",
                "person": {
                  "id": "435345345345345",
                  "first_name": "Jim",
                  "last_name": "Smith",
        },
 {
                "id": "56789",
                "person": {
                  "id": "3434534534543",
                  "first_name": "Tony",
                  "last_name": "Black",
        },

}

This returns the person

const id = this.people.find(person  => person.id === myid)


{
  "id": "435345345345345",
  "first_name": "Jim",
  "last_name": "Smith",
},

However I cannot see obvious way to get the id (12345). I have looked at all the standard array functions but nothing seems to be appropriate.

answered question

in this.people array are objects with object person ?

so it isn't nested array but object from your code example

Your input object is invalid.

2 Answers

13

I know you probably want to stick to the standard library but you could try doing it with lodash's find, https://lodash.com/docs/4.17.10#find

Here's an example returning the whole object:

https://runkit.com/rgomezs4/5be32606c9a3790013b4e4fc

posted this
9

You can use Array.find() method!

var myid = '435345345345345';

var  users = [
  {
    "id": "12345",
    "person": {
      "id": "435345345345345",
      "first_name": "Jim",
      "last_name": "Smith",
    }
  },

  {
    "id": "56789",
    "person": {
      "id": "3434534534543",
      "first_name": "Tony",
      "last_name": "Black",
    },
  }
];

var result = users.find(obj => obj.person.id === myid);
console.log('Object: ' + result);
console.log('Required ID: ' + result.id);

posted this

Have an answer?

JD

Please login first before posting an answer.