在数组中添加数据

时间:2016-06-06 12:43:53

标签: javascript data-manipulation

我有一些数据需要做一些计算/操作:

data=[{"sex":"M","age":"0","pop":"310"},
{"sex":"M","age":"5","pop":"306"},
{"sex":"M","age":"10","pop":"313"},
{"sex":"M","age":"15","pop":"332"},
....
{"sex":"M","age":"100","pop":"4"},
{"sex":"W","age":"0","pop":"294"},
{"sex":"W","age":"5","pop":"291"},
{"sex":"W","age":"10","pop":"300"},
{"sex":"W","age":"15","pop":"318"},
....
{"sex":"W","age":"100","pop":"1"}
]

我提取男性(M)和女性(W)的子数据:

var male=data.filter(function(d){
if (data.sex=="M"){return d.pop;}
})
var female=data.filter(function(d){
if (data.sex=="F"){return d.pop;}
})

现在,我想计算两性的人口(pop),即创建一个名为“both”的新变量,其中包含变量“age”:

both=[{"sex":"MW","age":"0","pop":"604"},
{"sex":"MW","age":"5","pop":"597"},
{"sex":"MW","age":"10","pop":"613"},
{"sex":"MW","age":"15","pop":"650",
....
{"sex":"MW","age":"100","pop":"5"}
]

我该怎么做?

3 个答案:

答案 0 :(得分:2)

听起来您希望将M和W条目组合成一个具有合并pop值的单个条目,按年龄。如果是这样,您需要按年龄创建条目的地图并将pop添加到一起,您可以使用对象在ES5中轻松完成(在ES2015中 - 也就是“ES6” - 您可能会使用一个Map)。完成后将其转换回数组。见评论:

// Your data -- note that I've fixed the pop values, if they're
// meant to be numbers, they shouldn't be in quotes
var data = [
    {"sex":"M","age":"0","pop":310},
    {"sex":"M","age":"5","pop":306},
    {"sex":"M","age":"10","pop":313},
    {"sex":"M","age":"15","pop":332},
    {"sex":"M","age":"100","pop":4},
    {"sex":"W","age":"0","pop":294},
    {"sex":"W","age":"5","pop":291},
    {"sex":"W","age":"10","pop":300},
    {"sex":"W","age":"15","pop":318},
    {"sex":"W","age":"100","pop":1}
];

// Create the "map" of entries by age:
var byAge = Object.create(null);
data.forEach(function(entry) {
    // Get the entry for this age, if any
    var ageEntry = byAge[entry.age];
    if (!ageEntry) {
        // None, create and add it with an initial pop of 0
        ageEntry = byAge[entry.age] = {sex: "MW", age: entry.age, pop: 0};
    }
  
    // Add in the pop for this entry
    ageEntry.pop += entry.pop;
});

// Convert it back into an array (if you want):
var result = Object.keys(byAge).map(function(key) {
    return byAge[key];
});

// Show result:
console.log(result);

答案 1 :(得分:2)

var data = [
    {"sex":"M","age":"0","pop":310},
    {"sex":"M","age":"5","pop":306},
    {"sex":"M","age":"10","pop":313},
    {"sex":"M","age":"15","pop":332},
    {"sex":"M","age":"100","pop":4},
    {"sex":"W","age":"0","pop":294},
    {"sex":"W","age":"5","pop":291},
    {"sex":"W","age":"10","pop":300},
    {"sex":"W","age":"15","pop":318},
    {"sex":"W","age":"100","pop":1}
];
var ages=[]
for(var i=0;i<data.lenght;i++){
   if(!ages[data[i]['age']]){
       ages[data[i]['age']].push({"sex": "MW", "age": data[i]['age'], "pop":data[i]['pop'] })
    }else{
      ages[data[i]['age']].pop +=data[i]['pop']
    }
}

答案 2 :(得分:0)

听起来,reduce方法可以满足您的需求。

`var population = ARR.reduce(function(a, b) {
      return Number(a.pop) + Number(b.pop);
 });`

请注意,您必须将填充的字符串表示形式转换为数字,否则它将被连接。