LaurenH
LaurenH

Reputation: 1

Accessing nested objects in javascript d3

I have data that looks like this (with multiple countries)

[
  {country:"Country1", GDP : 12345, GDPgrowth : {year1:123, year2:234, year3:345}},
  {country:"Country2", GDP : 12345, GDPgrowth : {year1:123, year2:234, year3:345}}
]

I am able to access each country's data by using a forEach and looping over the "rows".

However, I can't figure out how to access the individual values within GDPgrowth. I tried to do a nested forEach, but it throws an error about it not being a function, and I think it's because the data within GDPgrowth is not an array. I also tried a generic for loop approach but couldn't seem to achieve what I was looking for.

What is the recommended method for getting into these values (ideally without having to select by name year1, year2, year3 each time)?

Upvotes: 0

Views: 27

Answers (1)

Shidersz
Shidersz

Reputation: 17190

One solution is use Object.values() to get an array with the object values and you can use forEach() to iterate over they.

const input = [
    {country: "Country1", GDP: 12345, GDPgrowth: {year1:123, year2:234, year3:345}},
    {country:"Country2", GDP : 12345, GDPgrowth : {year1:123, year2:234, year3:345}}
];

input.forEach(x =>
{
    console.log("country: " + x.country);
    Object.values(x.GDPgrowth).forEach(y => console.log("year: " + y))
});

Also, I suggest to read about Object.keys() and Object.entries() too.

Upvotes: 1

Related Questions