简体   繁体   中英

How to iterate JSON with multiple levels?

Welcome, I got a problem with JSON file. I would like to iterate through it and get every status into array, but I got stuck. I load this file and parse it. Then I tried to use forEach but it did not worked. Thanks for help!

[{
  "offers": [{
    "advertiser_api_id": 12,
    "status": 1
  }, {
    "advertiser_api_id": 13,
    "status": 0
  }]
}]

I assume this will be in javascript. You can try the following:

for (x in json[0].offers) {
    console.log(json[0].offers[x].status);
}

You have got an array Of Objects inside Array.

Firstly, you need to parse the data from JSON to object using JSON.parse(data); Then, access the object offers . using the parsedData[0].offers object and then iterate over the array to get the status.

 var data = `[{ "offers": [{ "advertiser_api_id": 12, "status": 1 }, { "advertiser_api_id": 13, "status": 0 }] }]`; var parsedData = JSON.parse(data); var result = []; parsedData[0].offers.forEach((currentValue) => result.push(currentValue["status"])); console.log(result) 

You can use map function:

 var data = [{ "offers": [{ "advertiser_api_id": 12, "status": 1 }, { "advertiser_api_id": 13, "status": 0 }] }] var stats = data[0].offers.map(function(item) { return item.status; }) console.log(stats); 

This loops through the object and prints the data to console - you likely did not reach the correct array to loop through.

var data = [{
  "offers": [{
    "advertiser_api_id": 12,
    "status": 1
      }, {
    "advertiser_api_id": 13,
    "status": 0
  }]
}];

data[0].offers.forEach(function(element) {
  console.log(element.status);
});

This will work

statuses = []
JSON.parse(data)[0].offers.forEach(x => statuses.push(x.status))

A recursive approach

        var item = [{
      "offers": [{
        "advertiser_api_id": 12,
        "status": 1
      }, {
        "advertiser_api_id": 13,
        "status": 0
      }]
    }];

    var statusArray = [];
    function getStatusForALlLevels(item){
     if(item.offers instanceof Array){
     for(var i=0;i<item.offers.length;i++){
      getStatusForALlLevels(item.offers[i]);
      }
     }else{
       statusArray.push(item.status);
     }
    }
    getStatusForALlLevels(item[0]);
    console.log(statusArray);

You could use an iterative and recursive approach for getting status from multiple nested objects.

 var data = [{ offers: [{ advertiser_api_id: 12, status: 1 }, { advertiser_api_ii: 13, status: 0 }] }], status = data.reduce(function iter(r, o) { if ('status' in o) { r.push(o.status); } Object.keys(o).forEach(function (k) { if (Array.isArray(o[k])) { r = o[k].reduce(iter, r); } }); return r; }, []); console.log(status); 

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