gpt4 book ai didi

javascript - 在数组中添加数据

转载 作者:行者123 更新时间:2023-11-28 15:08:44 25 4
gpt4 key购买 nike

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

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"}
]

我该怎么做?

最佳答案

听起来您想将 M 和 W 条目合并为一个条目,并按年龄组合 pop 值。如果是这样,您需要按年龄创建条目的映射,并将 pop 添加在一起,您可以在 ES5 中使用对象轻松完成此操作(在 ES2015 中 — 又名“ES6” — 您d 可能使用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);

关于javascript - 在数组中添加数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37657816/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com