0

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

1 Answer 1

1

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.

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

2 Comments

Thank you so much! It's starting to make a little more sense and I'm off to read about Object.keys() and Object.entries().
@LaurenH you are welcome, consider to accept the answer if this helps you.

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.