简体   繁体   中英

looping through JSON object to get to the content of an array

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM