Skip to content Skip to sidebar Skip to footer

Jquery - Creating Nested Json From Flat Json

Below is the JSON data. JSON : [{ 'Code':'US-AL', 'Name':'Alabama', 'Population':4833722 }, { 'Code':'US-AK', 'Name':'Alaska', 'Population':735132

Solution 1:

Try this:

var newData = {};
data.forEach(function(val) {
    newData[val.Code] = {name: val.Name, population: val.Population};
});

Keep in mind that forEach isn't natively supported by IE8-, although it can be polyfilled. This works in every browser:

for (var i = 0; i < data.length; i++)
    newData[data[i].Code] = {name: data[i].Name, population: data[i].Population};

Or, since you added the "jquery" tag, you can also use:

$.each(data, function() {
    newData[this.Code] = {name: this.Name, population: this.Population};
});

Solution 2:

Try with native map of javascript

var newData = data.map(function (obj) {
    var newObj = {};
    newObj[obj.Code] = {};
    newObj[obj.Code].name = obj.Name;
    newObj[obj.Code].population = obj.Population;
    return newObj;
});

console.log(newData)

Solution 3:

[{"US-AL":{"name":"Alabama","population":4833722}},{"US-AK":{"name":"Alaska","population":735132}},{"US-AZ":{"name":"Arizona","population":6626624}},{"US-AR":{"name":"Arkansas","population":2959373}},{"US-CA":{"name":"California","population":38332521}},{"US-CO":{"name":"Colorado","population":5268367}},{"US-CT":{"name":"Connecticut","population":3596080}}]

And the code:

var newDatas = datas.map(function(item) {
    var obj = {};
    obj[item.Code] = { name: item.Name, population: item.Population };
    return obj;
});

datas is the array containing your original source.

Post a Comment for "Jquery - Creating Nested Json From Flat Json"