0

I have some JSON data that looks like this, where each object has three 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 to transform my data so that there are just two properties per object. The property named "country" would remain the same. I want to combine the other two properties, so that the value of "year" becomes the key of the new property, and the value of "number" is the value of the new property. So the new JSON array of objects would look like this:

    newData = [
      { 
          "country" : "Ireland", 
          "2013" : 45, 
          "2014" : 23430
      },
      { 
          "country" : "Honduras", 
          "2013" : 1582, 
          "2014" : 3458
      }
    ]

How would I go about doing that? I've done a lot of searching and can't find a solution. I'd prefer to just use javascript to do this and not a library.

2 Answers 2

1

Just go through each of the data items and add items to the result array. You can create a map to keep track of countries you've seen through the iteration for 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;
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much for your help!
0

Sorry, Here is the answer with javascript this time :

country_data = new Array();
for(l in data){
    if(typeof(country_data[data[l].country]) == 'undefined'){
       country_data[data[l].country] = new Array();
    }
    country_data[data[l].country].country = data[l]['country'];
    country_data[data[l].country][data[l].year] = data[l]['number'];
}

new_arr = new Array();
for(v in country_data){
    new_arr.push(country_data[v])
}

console.log(new_arr);

enter link description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.