两个阵列合并为一个;同时总结属性;与节点

时间:2015-01-28 15:11:36

标签: node.js mongodb merge count sum

我有两个来自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”做到这一点,但我试着避免那个因为代码会有很多很多的话。)

非常感谢!

1 个答案:

答案 0 :(得分:1)

略有临时性,但我就是这样做的。

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)等将其扩展到更多数组