i have json data looks this, each object has 3 properties:
data = [ { "country" : "ireland", "year" : "2013", "number" : 45 }, { "country" : "ireland", "year" : "2014", "number" : 23430 }, { "country" : "honduras", "year" : "2013", "number" : 1582 }, { "country" : "honduras", "year" : "2014", "number" : 3458 } ]
i want transform data there 2 properties per object. property named "country" remain same. want combine other 2 properties, value of "year" becomes key of new property, , value of "number" value of new property. new json array of objects this:
newdata = [ { "country" : "ireland", "2013" : 45, "2014" : 23430 }, { "country" : "honduras", "2013" : 1582, "2014" : 3458 } ]
how go doing that? i've done lot of searching , can't find solution. i'd prefer use javascript , not library.
just go through each of data items , add items result array. can create map keep track of countries you've seen through iteration quick access.
var newdata = [], countries = {}; data.foreach(function (d) { var country = countries[d.country]; if (!country) { newdata.push(country = countries[d.country] = {}); } country[d.year] = d.number; });
Comments
Post a Comment