简体   繁体   中英

Covert JSON objects inside json objects into a JSON Array in Javascript

Hello I have the following JSON structure and I try to make an array of each object inside each object but there is a way to convert it without iterating each element and get every element. Or maybe using a Javascript function to get object inside objects and convert to an array?

{
  "ES": {
    "130": {
      "code": "A Coruсa",
      "name": "A Coruña"
    },
    "131": {
      "code": "Alava",
      "name": "Alava"
    },
    "...": {
      "code": "...",
      "name": "..."
    }
  },
  "CH": {
    "104": {
      "code": "AG",
      "name": "Aargau"
    },
    "...": {
      "code": "...",
      "name": "..."
    }
  },
  "...": {
    "...": {
      "code": "...",
      "name": "..."
    }
  }
}

This is what I am looking for:

[
    {
      "code": "A Coruсa",
      "name": "A Coruña"
    },
    {
      "code": "Alava",
      "name": "Alava"
    },
    {
      "code": "...",
      "name": "..."
    },
    {
      "code": "AG",
      "name": "Aargau"
    },
    {
      "code": "...",
      "name": "..."
    },
    {
      "code": "...",
      "name": "..."
    }
]

Thanks for your help, I accept any recommendations.

You can use Object.keys() , Array.prototype.reduce() and Array.prototype.map() for iterating over the properties and for assembling the array.

 var obj = { "ES": { "130": { "code": "A Coruсa", "name": "A Coruña" }, "131": { "code": "Alava", "name": "Alava" }, }, "CH": { "104": { "code": "AG", "name": "Aargau" } } }, result = Object.keys(obj).reduce(function (r, k) { return r.concat(Object.keys(obj[k]).map(function (kk) { return obj[k][kk]; })); }, []); document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>'); 

I have created a fiddle to convert the data. look at it

https://jsbin.com/suzice/edit?js,output

  var data = {
  "ES": {
    "130": {
      "code": "A Coruсa",
      "name": "A Coruña"
    },
    "131": {
      "code": "Alava",
      "name": "Alava"
    },
    "...": {
      "code": "...",
      "name": "..."
    }
  },
  "CH": {
    "104": {
      "code": "AG",
      "name": "Aargau"
    },
    "...": {
      "code": "...",
      "name": "..."
    }
  }
};
var list = [];
Object.keys(data).forEach(function(key){

  Object.keys(data[key]).forEach(function(sub_key){
     list.push(data[key][sub_key]);
  });
  console.log(list);

});

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