0

I need to merge an array of objects. I am aware of jquery extend method

extend( target [, object1 ] [, objectN ] )

and that it can merge any number of objects.

But how do I loop through my array of the objects and merge them using this method?

niko craft
  • 2,893
  • 5
  • 38
  • 67
  • 1
    Possible duplicate of [How can I merge properties of two JavaScript objects dynamically?](http://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically) – gyre Mar 16 '17 at 00:04
  • not a duplicate, I know how to merge two javascript objects dynamically, that is easy, I have an array of objects that I need to merge, no idea how to do that. – niko craft Mar 16 '17 at 00:06
  • have you looked at underscore zip? – derp Mar 16 '17 at 00:09
  • nope, what is that exactly? – niko craft Mar 16 '17 at 00:09
  • 1
    If you know how to use `$.extend`, then this question is really just "how do I iterate over an array" unless there's something i'm missing. – CollinD Mar 16 '17 at 00:10
  • http://api.jquery.com/jquery.map/ ? – coltonb Mar 16 '17 at 00:12
  • @CollinD can you show me how this iteration would look like when you have more than 2 objects in the array? I have hard time visualizing this iteration and how it would work with extend – niko craft Mar 16 '17 at 00:22
  • managed to solve it, thanks guys – niko craft Mar 16 '17 at 00:28

1 Answers1

0

solved it:

  var object1 = {

  'perm-1': 1,
  'perm-2': 2,
  'perm-3': 3
};
var object2 = {
  'perm-1': 1,
  'perm-5': 5
};

var object3 = {
  'perm-6': 6,
  'perm-7': 7
};

var realArray = []

realArray.push(object1)
realArray.push(object2)
realArray.push(object3)

var target = {}

for(i=0; i<realArray.length; i++)
{
    $.extend(target, realArray[i])
}

$( "#log" ).append( JSON.stringify( target ) );
niko craft
  • 2,893
  • 5
  • 38
  • 67