0

I am breaking my head over this bit of code:

{
  "Carrefour": [
    { "geography": [ "Europe", "Germany" ], "productLine": "Produce", "revenue": { "2022": 130143, "2021": 172122, "2020": 103716 } },
    { "geography": [ "Europe", "France" ], "productLine": "Clothing", "revenue": { "2022": 85693, "2021": 91790, "2020": 77650 } },
    ],
  "Tesco": [
    { "geography": [ "Europe", "United Kingdom" ], "productLine": "Electronics", "revenue": { "2022": 239537, "2021": 131959, "2020": 97047 } },
    { "geography": [ "Europe", "Ireland" ], "productLine": "Produce", "revenue": { "2022": 74963, "2021": 43406, "2020": 54623 } },
    ]
}

I am trying to loop through this code to get to all the content.

But to begn with I don't know how to get to the region (Europe). I tried

function (json) {
    for (var company in json) {
        region = json[company].geography[0];
    }
}

But it returns undefined, because company is an array. Infact json.Carrefour[0].geography[0]; returns correctly "Europe".

how do I access company as an array and retain the name? I can't use the name directly!

Thank you.

0

1 Answer 1

1

Your companies are assigned Arrays, so you need an inner loop.

for (var company in json) {
    for (var i = 0; i < json[company].length; i++) {
        region = json[company][i].geography[0];
    }
}

Here's a demo: http://jsfiddle.net/dkPWt/

Demo output:

Carrefour: 
    Europe
    Europe
Tesco: 
    Europe
    Europe
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.