rashadb
rashadb

Reputation: 2543

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.

[N] = is an array of N objects each of which has about 10 key value pairs within.

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. I'd like to keep the values from both so that key1: [9].

Upvotes: 1

Views: 98

Answers (2)

Ja͢ck
Ja͢ck

Reputation: 173642

This is not an underscore answer, but basically I wouldn't use a reduce operation for this and instead do a simple 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]}

Upvotes: 2

RobG
RobG

Reputation: 147453

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

Upvotes: 1

Related Questions