Vlad Vlad - 1 month ago 5
Javascript Question

How to concatenate properties from multiple JavaScript objects

I am looking for the best way to "add" multiple JavaScript objects (associative arrays).

For example, given:

a = { "one" : 1, "two" : 2 };
b = { "three" : 3 };
c = { "four" : 4, "five" : 5 };


what is the best way to compute:

{ "one" : 1, "two" : 2, "three" : 3, "four" : 4, "five" : 5 }

Answer

This should do it:

function collect() {
  var ret = {};
  var len = arguments.length;
  for (var i=0; i<len; i++) {
    for (p in arguments[i]) {
      if (arguments[i].hasOwnProperty(p)) {
        ret[p] = arguments[i][p];
      }
    }
  }
  return ret;
}

Input:

a = { "one" : 1, "two" : 2 };
b = { "three" : 3 };
c = { "four" : 4, "five" : 5 };
d = collect(a, b, c);
console.log(d);

Output:

Object one=1 two=2  three=3 four=4 five=5