将对象中的值添加到对象数组而不覆盖现有键值

时间:2015-06-11 03:28:44

标签: javascript arrays object underscore.js

你怎么做的:

var array = [{key: [3]}, {key1: [3]}, {key1: [3]}]
var object = {key1: [3], key2: [3]};

到此:

{key: [3], key1: [9], key2: [3]}

所有"关键"是一个像" LQVjUacPgK"如下面的obj示例所示。

[N] =是一个N个对象的数组,每个对象都有大约10个键值对。

N = {obj, obj, obj};

obj = {_account: "JDQEPxoy3ktZRP9VEzAMtXLa7rXXedhQ4bARq"
_id: "oQER3vznDwikxm1wdLzJFdVjKL6XomcORMxDL"
amount: 170
category: Array[2]
category_id: "21003000"
date: "2015-06-09"Object
type: Object
userId: "LQVjUacPgK"}

现在我正在这样做:

var test = _.reduce(_.flatten(array.concat([object])),function(a,b){
     return _.extend(a, b);
       });
    }
};

取而代之的是这个结果:

console.log(test)//{key: [3], key1: [3], key2: [3]}

要清楚,问题是key1在所有对象之间具有不同的值。我想保留两者的值,以便 key1:[9]

2 个答案:

答案 0 :(得分:2)

这不是一个下划线的答案,但基本上我不会为此使用reduce操作,而是做一个简单的for-each:

var array = [{key: [3]}, {key1: [3]}, {key1: [3]}]
var object = {key1: [3], key2: [3]};

array.forEach(function(current) {
  Object.keys(current).forEach(function(name) {
//        object[name] = [((object[name] || [])[0] || 0) + current[name][0]];
      object[name] = (object[name] || []).concat(current[name]);
  });
});

console.log(JSON.stringify(object)); // {"key1":[3,3,3],"key2":[3],"key":[3]}

答案 1 :(得分:1)

与Jack的答案(也是非下划线)类似,但它会创建一个新对象,但它不会修改现有的对象对象:

var array = [{key: [3]}, {key1: [3]}, {key1: [3]}]
var object = {key1: [3], key2: [3]};

var x = array.concat([object]).reduce(function(prev, curr) {
  Object.keys(curr).forEach(function(key){
    if (prev.hasOwnProperty(key)) {
      prev[key][0] += curr[key][0];
    } else {
      prev[key] = curr[key];
    }
  });
  return prev;
},{});

console.log(JSON.stringify(x));  // {"key":[3],"key1":[9],"key2":[3]}