Home > OS >  Get a value from an object inside an object
Get a value from an object inside an object

Time:03-09

How do I get the id 43 from country ?

"hq_locations":[{"id":1886112,"address":"10 Rue Laurencin, 69002 Lyon, France","street":"Rue Laurencin","street_number":"10","zip":"69002","lat":45.7527311,"lon":4.8321804,"country":{"id":43,"name":"France","lat":46.227638,"lon":2.213749,"trade_register_office":"Info Greffe"}

CodePudding user response:

The reason why it is probably not working is because you the hq_locations contains an array that contains an object that contains a child object and some properties.

As you can see the levels you have to bypass before you get to the id of the country is more than just the selecting the object in the object and then its property.

An example to access the first element in the row:

const obj = {
    "hq_locations": [{
        "id": 1886112,
        "address": "10 Rue Laurencin, 69002 Lyon, France",
        "street": "Rue Laurencin",
        "street_number": "10",
        "zip": "69002",
        "lat": 45.7527311,
        "lon": 4.8321804,
        "country": {
            "id": 43,
            "name": "France",
            "lat": 46.227638,
            "lon": 2.213749,
            "trade_register_office": "Info Greffe"
        }
    }]
};

console.log(obj.hq_locations[0].country.id)

If you want to access all the elements in the array and select all the ids you'd have to loop it:

   for (let i = 0; i < obj.hq_locations.length; i  ) {
    console.log(obj.hq_locations[i].id)
}
  • Related