Dmitry
Dmitry

Reputation: 89

Creating object in a loop

I have a json file with companies and countries. What is the most correct way to create an object.The cycle goes through all countries, and I have to calculate how many companies are related to a particular country, in order to get the object as a result, approximately the following format:

country = {
   USA: 13, 
   Germany: 11,
   Belgia: 3
}

Upvotes: 0

Views: 42

Answers (2)

christo8989
christo8989

Reputation: 6826

You will want to JSON.parse the json and use Array.reduce to get your object.

var companies = JSON.parse(json).list; //<-- unsafe for production
var countries = companies.reduce(function(countries, company) {
    var country = company.location.name;
    if (typeof countries[country] === 'undefined' || countries[country] === null) {
        countries[country] = 1;
    } else {
        countries[country]++;
    }

    return countries;
}, {});

Upvotes: 1

Ivar
Ivar

Reputation: 6857

You can try something like this: (Using the object data you had in your question before the edit.)

var jsondata = {"list":[{"name":"Photolist","location":{"name":"Poland","code":"PL"},"partners":[{"name":"Oloo","value":30},{"name":"Flashset","value":87}]},{"name":"Mymm","location":{"name":"Ukraine","code":"UA"},"partners":[{"name":"Photojam","value":57},{"name":"Divavu","value":82},{"name":"Quinu","value":18}]},{"name":"Yata","location":{"name":"United States","code":"US"},"partners":[{"name":"Meetz","value":72}]},{"name":"Brainbox","location":{"name":"Norway","code":"NO"},"partners":[{"name":"Divavu","value":42}]},{"name":"Flashpoint","location":{"name":"Sweden","code":"SE"},"partners":[{"name":"Babbleopia","value":53},{"name":"Buzzdog","value":70},{"name":"Voolia","value":20}]},{"name":"Photospace","location":{"name":"Poland","code":"PL"},"partners":[{"name":"Yakitri","value":81},{"name":"Divavu","value":85},{"name":"Skimia","value":12},{"name":"Meeveo","value":27}]},{"name":"Realfire","location":{"name":"Poland","code":"PL"},"partners":[{"name":"Topicshots","value":81}]}]};

var countries = {};
jsondata.list.forEach(function (elem) {
    if (elem.location.name in countries) { 
        countries[elem.location.name]++;
    } else {
        countries[elem.location.name] = 1; 
    }
});

console.log(countries);

Upvotes: 1

Related Questions