通过添加数字属性,在数组中合并具有相同id的对象

时间:2017-03-05 07:30:59

标签: javascript

我已经在谷歌搜索了一个教程但找不到我需要的东西。 我有一个像这样的数组:

[
 {Username:'user1', Balance:'123'}, 
 {Username:'user2', Balance:'213'}, 
 {Username:'user1', Balance:'424'}
]

Balance相同时如何合并Username,例如合并余额 Username:'user1'

3 个答案:

答案 0 :(得分:1)

当某些属性匹配时,您可以结合使用更高级别的内置函数(如Object.keysArray#reduceArray#map来有条理地组合数组条目。

var array = [{
  Username: 'user1',
  Balance: '123'
}, {
  Username: 'user2',
  Balance: '213'
}, {
  Username: 'user1',
  Balance: '424'
}]

var map = array.reduce(function (map, e) {
  map[e.Username] = +e.Balance + (map[e.Username] || 0) 
  return map
}, {})

var result = Object.keys(map).map(function (k) {
  return { Username: k, Balance: map[k] }
})

console.log(result)

编辑:OP要求答案足够灵活,以处理多个媒体资源。我也将保留原始片段,最后我认为其中一个更优雅。

var array = [{
  Username: 'user1',
  Balance: '123',
  Another: '222'
}, {
  Username: 'user2',
  Balance: '213',
  Another: '111'
}, {
  Username: 'user1',
  Balance: '424',
  Another: '121'
}]

// Add elements to this array if you need to handle more properties
var properties = ['Balance', 'Another']

var map = array.reduce(function (map, e) {
  map[e.Username] = properties.map(function (property, i) {
    return +e[property] + ((map[e.Username] || [])[i] || 0)
  })
  return map
}, {})

var result = Object.keys(map).map(function (k) {
  return map[k].reduce(function (object, e, i) {
    object[properties[i]] = e
    return object
  }, { Username: k })
})

console.log(result)

答案 1 :(得分:1)

您可以使用带有哈希表的单个循环来引用具有相同Username的对象。



var data = [{ Username: 'user1', Balance: '123' }, { Username: 'user2', Balance: '213' }, { Username: 'user1', Balance: '424' }],
    grouped = [];
    
data.forEach(function (hash) {
    return function (o) {
        if (!hash[o.Username]) {
            hash[o.Username] = { Username: o.Username, Balance: 0 };
            grouped.push(hash[o.Username]);
        }
        hash[o.Username].Balance += +o.Balance;
    };
}(Object.create(null)));

console.log(grouped);




答案 2 :(得分:0)

这里还有一个解决方案,我觉得这个问题比gyre的还要少(但我也很感兴趣)。



function mergeBalances(x) {
    var users = [];
    users = x.filter(function(entry) {
                        if(users[entry.Username]) { return false;}
                        users[entry.Username] = entry.Username;
                        return true;
                     })
             .map(function(e) { return e.Username; } );

    balances = {};
    for(var i=0; i < users.length; i++) {
            balances[i] = { Username:users[i]};
            balances[i].Balance = x.filter(function(e) { return e.Username==users[i]; })
                                   .reduce(function(total, e) { return total + eval(e.Balance);}, 0);
    }

    return balances;
}

// just call the function on your array
x = [ {Username:'user1', Balance:'123'}, {Username:'user2', Balance:'213'}, {Username:'user1', Balance:'424'} ]
console.log(mergeBalances(x));
&#13;
&#13;
&#13;