在循环中创建对象

时间:2017-09-02 14:53:20

标签: javascript

我有一个公司和国家/地区的json文件。什么是最正确的创建对象的方法。循环遍历所有国家/地区,我必须计算有多少公司与特定国家/地区相关,以便获得对象,大致采用以下格式:

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

2 个答案:

答案 0 :(得分:1)

你可以尝试这样的事情:(在编辑之前使用问题中的对象数据。)



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);




答案 1 :(得分:1)

您需要JSON.parse json并使用Array.reduce来获取您的对象。

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;
}, {});