两个数组合并为一个;同时对属性求和;有节点
Two Arrays merged to one; while sum the attributes; with nodes
我有两个来自 mongodb 的数组,我想合并它们。
它们看起来像这样:
a=[{country: 'de', count: 7},{country: 'es', count: 1}]
b=[{country: 'de', count: 2}, {country: 'us', count: 3}]
我需要的是:
c=[{country: 'de', count: 9},{country: 'us', count: 3},{country: 'es', count: 1}]
有没有不循环每个可能的密钥对的智能方法来使用 nodejs 完成此操作?
(我可以用很多 "for's" 来做,但我尽量避免这种情况,因为那时代码会有很多很多。)
非常感谢!
有点特别,但我就是这样做的。
a = [{country: 'de', count: 7}, {country: 'es', count: 1}]
b = [{country: 'de', count: 2}, {country: 'us', count: 3}]
temp = {}
c = []
merger = function (entry) {
key = entry.country
if (typeof temp[key] == 'undefined')
temp[key] = 0
temp[key] += entry.count
}
a.forEach(merger)
b.forEach(merger)
for (country in temp) {
c.push({ country: country, count: temp[country] })
}
我已经在 Node 的 REPL 中测试过了。请注意,您可以使用 c.forEach(merger)
等将其扩展到更多数组
我有两个来自 mongodb 的数组,我想合并它们。
它们看起来像这样:
a=[{country: 'de', count: 7},{country: 'es', count: 1}]
b=[{country: 'de', count: 2}, {country: 'us', count: 3}]
我需要的是:
c=[{country: 'de', count: 9},{country: 'us', count: 3},{country: 'es', count: 1}]
有没有不循环每个可能的密钥对的智能方法来使用 nodejs 完成此操作?
(我可以用很多 "for's" 来做,但我尽量避免这种情况,因为那时代码会有很多很多。)
非常感谢!
有点特别,但我就是这样做的。
a = [{country: 'de', count: 7}, {country: 'es', count: 1}]
b = [{country: 'de', count: 2}, {country: 'us', count: 3}]
temp = {}
c = []
merger = function (entry) {
key = entry.country
if (typeof temp[key] == 'undefined')
temp[key] = 0
temp[key] += entry.count
}
a.forEach(merger)
b.forEach(merger)
for (country in temp) {
c.push({ country: country, count: temp[country] })
}
我已经在 Node 的 REPL 中测试过了。请注意,您可以使用 c.forEach(merger)
等将其扩展到更多数组