简体   繁体   English

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

[英]Adding the values from an object to an array of objects without overriding existing key values

How do you go from this: 你怎么做的:

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

to this: 对此:

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

All "key" are a userIds like "LQVjUacPgK" as seen in the obj example below. 所有“key”都是像“LQVjUacPgK”这样的userIds,如下面的obj示例所示。

[N] = is an array of N objects each of which has about 10 key value pairs within. [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"}

Right now I'm doing this: 现在我这样做:

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

and getting this result instead: 而得到这个结果:

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

To be clear, the issue is that key1 has different values between all of the objects. 要清楚,问题是key1在所有对象之间具有不同的值。 I'd like to keep the values from both so that key1: [9] . 我想保留两者的值,以便key1:[9]

This is not an underscore answer, but basically I wouldn't use a reduce operation for this and instead do a simple for-each: 这不是一个下划线的答案,但基本上我不会为此使用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]} 

Similar to Jack's answer (also non-underscore), but it creates a new object, it doesn't modify the existing object Object: 类似杰克的答案(也非下划线),但它创建了一个新的对象,它不修改现有对象的对象:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM