Rectangle 27 24

You can use Object.assign() to merge them into a new object:

You can also use object spread, which is a Stage 3 proposal for ECMAScript, and requires Babel's Object rest spread transform (included in Stage 3 preset) to use:

const response = {
  lat: -51.3303,
  lng: 0.39440
}

let item = {
  id: 'qwenhee-9763ae-lenfya',
  address: '14-22 Elder St, London, E1 6BT, UK'
}

const newItem = { ...item, location: response };

console.log(newItem );

javascript - Merge two objects with ES6 - Stack Overflow

javascript ecmascript-6
Rectangle 27 29

Merge properties of N objects in one line of code

An Object.assign method is part of the ECMAScript 2015 (ES6) standard and does exactly what you need. (IE not supported)

var clone = Object.assign({}, obj);

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object.

if (!Object.assign) {
  Object.defineProperty(Object, 'assign', {
    enumerable: false,
    configurable: true,
    writable: true,
    value: function(target) {
      'use strict';
      if (target === undefined || target === null) {
        throw new TypeError('Cannot convert first argument to object');
      }

      var to = Object(target);
      for (var i = 1; i < arguments.length; i++) {
        var nextSource = arguments[i];
        if (nextSource === undefined || nextSource === null) {
          continue;
        }
        nextSource = Object(nextSource);

        var keysArray = Object.keys(nextSource);
        for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
          var nextKey = keysArray[nextIndex];
          var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
          if (desc !== undefined && desc.enumerable) {
            to[nextKey] = nextSource[nextKey];
          }
        }
      }
      return to;
    }
  });
}

what does 'use strict' do in older browsersm or why is it there at all. browsers that support object[defineProperty; keys; getOwnPropertyDescriptor; etc], are not exactly old. They're just earlier versions of gen.5 UAs.

Thanks for clarifying that Objects.assign returns a merged object which the other answers don't. That's more functional programming style.

How can I merge properties of two JavaScript objects dynamically? - St...

javascript javascript-objects
Rectangle 27 29

Merge properties of N objects in one line of code

An Object.assign method is part of the ECMAScript 2015 (ES6) standard and does exactly what you need. (IE not supported)

var clone = Object.assign({}, obj);

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object.

if (!Object.assign) {
  Object.defineProperty(Object, 'assign', {
    enumerable: false,
    configurable: true,
    writable: true,
    value: function(target) {
      'use strict';
      if (target === undefined || target === null) {
        throw new TypeError('Cannot convert first argument to object');
      }

      var to = Object(target);
      for (var i = 1; i < arguments.length; i++) {
        var nextSource = arguments[i];
        if (nextSource === undefined || nextSource === null) {
          continue;
        }
        nextSource = Object(nextSource);

        var keysArray = Object.keys(nextSource);
        for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
          var nextKey = keysArray[nextIndex];
          var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
          if (desc !== undefined && desc.enumerable) {
            to[nextKey] = nextSource[nextKey];
          }
        }
      }
      return to;
    }
  });
}

what does 'use strict' do in older browsersm or why is it there at all. browsers that support object[defineProperty; keys; getOwnPropertyDescriptor; etc], are not exactly old. They're just earlier versions of gen.5 UAs.

Thanks for clarifying that Objects.assign returns a merged object which the other answers don't. That's more functional programming style.

How can I merge properties of two JavaScript objects dynamically? - St...

javascript javascript-objects
Rectangle 27 77

Similar to jQuery extend(), you have the same function in AngularJS:

// Merge the 'options' object into the 'settings' object
var settings = {validate: false, limit: 5, name: "foo"};
var options  = {validate: true, name: "bar"};
angular.extend(settings, options);

you can also "borrow" extend's definition from JQ source...

@naXa I think it'd be an option if you don't want to add a lib just for this fn.

How can I merge properties of two JavaScript objects dynamically? - St...

javascript javascript-objects
Rectangle 27 77

Similar to jQuery extend(), you have the same function in AngularJS:

// Merge the 'options' object into the 'settings' object
var settings = {validate: false, limit: 5, name: "foo"};
var options  = {validate: true, name: "bar"};
angular.extend(settings, options);

you can also "borrow" extend's definition from JQ source...

@naXa I think it'd be an option if you don't want to add a lib just for this fn.

How can I merge properties of two JavaScript objects dynamically? - St...

javascript javascript-objects
Rectangle 27 1474

/* For the case in question, you would do: */
Object.assign(obj1, obj2);

/** There's no limit to the number of objects you can merge.
 *  All objects get merged into the first object. 
 *  Only the object in the first argument is mutated and returned.
 *  Later properties overwrite earlier properties with the same name. */
const allRules = Object.assign({}, obj1, obj2, obj3, etc);

Method for ES5 and Earlier

for (var attrname in obj2) { obj1[attrname] = obj2[attrname]; }

Note that this will simply add all attributes of obj2 to obj1 which might not be what you want if you still want to use the unmodified obj1.

If you're using a framework that craps all over your prototypes then you have to get fancier with checks like hasOwnProperty, but that code will work for 99% of cases.

/**
 * Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1
 * @param obj1
 * @param obj2
 * @returns obj3 a new object based on obj1 and obj2
 */
function merge_options(obj1,obj2){
    var obj3 = {};
    for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
    for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
    return obj3;
}

This doesn't work if objects have same name attributes, and you would also want to merge the attributes.

This only does a shallow copy/merge. Has the potential to clobber a lot of elements.

+1 for acknowledging that some poor souls are forced to use frameworks that crap all over their prototypes...

Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1

@scones I think he's talking about how the two are merged. I.e. Overwrites obj1's values (in obj3) with obj2's and adds obj2's (to obj3) if non existent in obj1

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

How can I merge properties of two JavaScript objects dynamically? - St...

javascript javascript-objects
Rectangle 27 1456

/* For the case in question, you would do: */
Object.assign(obj1, obj2);

/** There's no limit to the number of objects you can merge.
 *  All objects get merged into the first object. 
 *  Only the object in the first argument is mutated and returned.
 *  Later properties overwrite earlier properties with the same name. */
const allRules = Object.assign({}, obj1, obj2, obj3, etc);

Method for ES5 and Earlier

for (var attrname in obj2) { obj1[attrname] = obj2[attrname]; }

Note that this will simply add all attributes of obj2 to obj1 which might not be what you want if you still want to use the unmodified obj1.

If you're using a framework that craps all over your prototypes then you have to get fancier with checks like hasOwnProperty, but that code will work for 99% of cases.

/**
 * Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1
 * @param obj1
 * @param obj2
 * @returns obj3 a new object based on obj1 and obj2
 */
function merge_options(obj1,obj2){
    var obj3 = {};
    for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
    for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
    return obj3;
}

This doesn't work if objects have same name attributes, and you would also want to merge the attributes.

This only does a shallow copy/merge. Has the potential to clobber a lot of elements.

+1 for acknowledging that some poor souls are forced to use frameworks that crap all over their prototypes...

Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1

@scones I think he's talking about how the two are merged. I.e. Overwrites obj1's values (in obj3) with obj2's and adds obj2's (to obj3) if non existent in obj1

How can I merge properties of two JavaScript objects dynamically? - St...

javascript javascript-objects
Rectangle 27 213

I googled for code to merge object properties and ended up here. However since there wasn't any code for recursive merge I wrote it myself. (Maybe jQuery extend is recursive BTW?) Anyhow, hopefully someone else will find it useful as well.

(Now the code does not use Object.prototype :)

/*
* Recursively merge properties of two objects 
*/
function MergeRecursive(obj1, obj2) {

  for (var p in obj2) {
    try {
      // Property in destination object set; update its value.
      if ( obj2[p].constructor==Object ) {
        obj1[p] = MergeRecursive(obj1[p], obj2[p]);

      } else {
        obj1[p] = obj2[p];

      }

    } catch(e) {
      // Property in destination object not set; create it and set its value.
      obj1[p] = obj2[p];

    }
  }

  return obj1;
}
o1 = {  a : 1,
        b : 2,
        c : {
          ca : 1,
          cb : 2,
          cc : {
            cca : 100,
            ccb : 200 } } };

o2 = {  a : 10,
        c : {
          ca : 10,
          cb : 20, 
          cc : {
            cca : 101,
            ccb : 202 } } };

o3 = MergeRecursive(o1, o2);
o3 = {  a : 10,
        b : 2,
        c : {
          ca : 10,
          cb : 20,
          cc : { 
            cca : 101,
            ccb : 202 } } };

Nice, but I would make a deepcopy of the objects first. This way o1 would be modified too, as objects are passed by reference.

This was what I was looking for. Make sure to check if obj2.hasOwnProperty(p) before you go to the try catch statement. Otherwise, you might end up with some other crap getting merged in from higher up in the prototype chain.

Thanks Markus. Note that o1 is also modified by MergeRecursive, so at the end, o1 and o3 are identical. It might be more intuitive if you don't return anything, so the user knows that what they're supplying (o1) gets modified and becomes the result. Also, in your example, it might be worth adding something into o2 that isn't originally in o1, to show that o2 properties get inserted into o1 (someone else below submitted alternative code copying your example, but theirs breaks when o2 contains properties not in o1 - but yours works in this respect).

@JonoRR - the call to itself makes it recursive: obj1[p] = MergeRecursive(obj1[p], obj2[p]);

This is a good answer, but a couple quibbles: 1) No logic should be based on exceptions; in this case, any exception thrown will be caught with unpredictable results. 2)I agree with @pancake's comment about not returning anything, since the original object is modified. Here's a jsFiddle example without the exception logic: jsfiddle.net/jlowery2663/z8at6knn/4 Jeff Lowery

How can I merge properties of two JavaScript objects dynamically? - St...

javascript javascript-objects
Rectangle 27 212

I googled for code to merge object properties and ended up here. However since there wasn't any code for recursive merge I wrote it myself. (Maybe jQuery extend is recursive BTW?) Anyhow, hopefully someone else will find it useful as well.

(Now the code does not use Object.prototype :)

/*
* Recursively merge properties of two objects 
*/
function MergeRecursive(obj1, obj2) {

  for (var p in obj2) {
    try {
      // Property in destination object set; update its value.
      if ( obj2[p].constructor==Object ) {
        obj1[p] = MergeRecursive(obj1[p], obj2[p]);

      } else {
        obj1[p] = obj2[p];

      }

    } catch(e) {
      // Property in destination object not set; create it and set its value.
      obj1[p] = obj2[p];

    }
  }

  return obj1;
}
o1 = {  a : 1,
        b : 2,
        c : {
          ca : 1,
          cb : 2,
          cc : {
            cca : 100,
            ccb : 200 } } };

o2 = {  a : 10,
        c : {
          ca : 10,
          cb : 20, 
          cc : {
            cca : 101,
            ccb : 202 } } };

o3 = MergeRecursive(o1, o2);
o3 = {  a : 10,
        b : 2,
        c : {
          ca : 10,
          cb : 20,
          cc : { 
            cca : 101,
            ccb : 202 } } };

Nice, but I would make a deepcopy of the objects first. This way o1 would be modified too, as objects are passed by reference.

This was what I was looking for. Make sure to check if obj2.hasOwnProperty(p) before you go to the try catch statement. Otherwise, you might end up with some other crap getting merged in from higher up in the prototype chain.

Thanks Markus. Note that o1 is also modified by MergeRecursive, so at the end, o1 and o3 are identical. It might be more intuitive if you don't return anything, so the user knows that what they're supplying (o1) gets modified and becomes the result. Also, in your example, it might be worth adding something into o2 that isn't originally in o1, to show that o2 properties get inserted into o1 (someone else below submitted alternative code copying your example, but theirs breaks when o2 contains properties not in o1 - but yours works in this respect).

@JonoRR - the call to itself makes it recursive: obj1[p] = MergeRecursive(obj1[p], obj2[p]);

This is a good answer, but a couple quibbles: 1) No logic should be based on exceptions; in this case, any exception thrown will be caught with unpredictable results. 2)I agree with @pancake's comment about not returning anything, since the original object is modified. Here's a jsFiddle example without the exception logic: jsfiddle.net/jlowery2663/z8at6knn/4 Jeff Lowery

How can I merge properties of two JavaScript objects dynamically? - St...

javascript javascript-objects
Rectangle 27 157

First concatenate the two arrays, next filter out only the unique items.

As suggested by @Dmitry (see the second comment below) a more performance wise solution would be to filter out the unique items in b before concatenating with a

var a = [1, 2, 3], b = [101, 2, 1, 10];
var c = a.concat(b.filter(function (item) {
    return a.indexOf(item) < 0;
}));

// d is [1,2,3,101,10]

Good example. However.. Let sizes of array are A = |a|, B = |b| etc. In the worst case you will use (A + B) * 4 memory for array items. A better approach would be filter before the concatenation, as in jsfiddle.net/98622/75

The original solution here has the benefit of removing dupes within each source array. I guess it depends on your context which you would use.

a.forEach(function(item){ if(a.indexOf(item)<0) a.push(item); });

Just a reminder of the current browser usage caniuse.com/usage-table for people anxious about IE6.

var c = [...a, ...b.filter(o => !~a.indexOf(o))];
var c = [...new Set([...a, ...b])];

How to merge two arrays in JavaScript and de-duplicate items - Stack O...

javascript arrays merge
Rectangle 27 154

First concatenate the two arrays, next filter out only the unique items.

As suggested by @Dmitry (see the second comment below) a more performance wise solution would be to filter out the unique items in b before concatenating with a

var a = [1, 2, 3], b = [101, 2, 1, 10];
var c = a.concat(b.filter(function (item) {
    return a.indexOf(item) < 0;
}));

// d is [1,2,3,101,10]

The original solution here has the benefit of removing dupes within each source array. I guess it depends on your context which you would use.

a.forEach(function(item){ if(a.indexOf(item)<0) a.push(item); });

Just a reminder of the current browser usage caniuse.com/usage-table for people anxious about IE6.

var c = [...a, ...b.filter(o => !~a.indexOf(o))];
var c = [...new Set([...a, ...b])];

How to merge two arrays in JavaScript and de-duplicate items - Stack O...

javascript arrays merge
Rectangle 27 51

I need to merge objects today, and this question (and answers) helped me a lot. I tried some of the answers, but none of them fit my needs, so I combined some of the answers, added something myself and came up with a new merge function. Here it is:

var merge = function() {
    var obj = {},
        i = 0,
        il = arguments.length,
        key;
    for (; i < il; i++) {
        for (key in arguments[i]) {
            if (arguments[i].hasOwnProperty(key)) {
                obj[key] = arguments[i][key];
            }
        }
    }
    return obj;
};
var t1 = {
    key1: 1,
    key2: "test",
    key3: [5, 2, 76, 21]
};
var t2 = {
    key1: {
        ik1: "hello",
        ik2: "world",
        ik3: 3
    }
};
var t3 = {
    key2: 3,
    key3: {
        t1: 1,
        t2: 2,
        t3: {
            a1: 1,
            a2: 3,
            a4: [21, 3, 42, "asd"]
        }
    }
};

console.log(merge(t1, t2));
console.log(merge(t1, t3));
console.log(merge(t2, t3));
console.log(merge(t1, t2, t3));
console.log(merge({}, t1, { key1: 1 }));

This is a great answer! It is just like the jQuery source code!

The only tag for question is javascript, so this is the only correct answer and also great one.

good answer but i think if a property is present in the first one and in second and you are trying to make a new object by merging first and second then the unique ones present in first object will be lost

But isn't it expected behaviour? This function's purpose is override values in argument order. Next one will override current. How can you preserve unique values? From my example, what do you expect from merge({}, t1, { key1: 1 })?

How can I merge properties of two JavaScript objects dynamically? - St...

javascript javascript-objects
Rectangle 27 51

I need to merge objects today, and this question (and answers) helped me a lot. I tried some of the answers, but none of them fit my needs, so I combined some of the answers, added something myself and came up with a new merge function. Here it is:

var merge = function() {
    var obj = {},
        i = 0,
        il = arguments.length,
        key;
    for (; i < il; i++) {
        for (key in arguments[i]) {
            if (arguments[i].hasOwnProperty(key)) {
                obj[key] = arguments[i][key];
            }
        }
    }
    return obj;
};
var t1 = {
    key1: 1,
    key2: "test",
    key3: [5, 2, 76, 21]
};
var t2 = {
    key1: {
        ik1: "hello",
        ik2: "world",
        ik3: 3
    }
};
var t3 = {
    key2: 3,
    key3: {
        t1: 1,
        t2: 2,
        t3: {
            a1: 1,
            a2: 3,
            a4: [21, 3, 42, "asd"]
        }
    }
};

console.log(merge(t1, t2));
console.log(merge(t1, t3));
console.log(merge(t2, t3));
console.log(merge(t1, t2, t3));
console.log(merge({}, t1, { key1: 1 }));

This is a great answer! It is just like the jQuery source code!

The only tag for question is javascript, so this is the only correct answer and also great one.

good answer but i think if a property is present in the first one and in second and you are trying to make a new object by merging first and second then the unique ones present in first object will be lost

But isn't it expected behaviour? This function's purpose is override values in argument order. Next one will override current. How can you preserve unique values? From my example, what do you expect from merge({}, t1, { key1: 1 })?

How can I merge properties of two JavaScript objects dynamically? - St...

javascript javascript-objects
Rectangle 27 13

Why don't you use an object? It looks like you're trying to model a set. This won't preserve the order, however.

var set1 = {"Vijendra":true, "Singh":true}
var set2 = {"Singh":true,  "Shakya":true}

// Merge second object into first
function merge(set1, set2){
  for (var key in set2){
    if (set2.hasOwnProperty(key))
      set1[key] = set2[key]
  }
  return set1
}

merge(set1, set2)

// Create set from array
function setify(array){
  var result = {}
  for (var item in array){
    if (array.hasOwnProperty(item))
      result[array[item]] = true
  }
  return result
}
if (!set1.hasOwnProperty(key))

Why would I mean that? The purpose of that condition is to ignore properties that may be in the object's prototype.

How to merge two arrays in JavaScript and de-duplicate items - Stack O...

javascript arrays merge
Rectangle 27 13

Why don't you use an object? It looks like you're trying to model a set. This won't preserve the order, however.

var set1 = {"Vijendra":true, "Singh":true}
var set2 = {"Singh":true,  "Shakya":true}

// Merge second object into first
function merge(set1, set2){
  for (var key in set2){
    if (set2.hasOwnProperty(key))
      set1[key] = set2[key]
  }
  return set1
}

merge(set1, set2)

// Create set from array
function setify(array){
  var result = {}
  for (var item in array){
    if (array.hasOwnProperty(item))
      result[array[item]] = true
  }
  return result
}
if (!set1.hasOwnProperty(key))

Why would I mean that? The purpose of that condition is to ignore properties that may be in the object's prototype.

How to merge two arrays in JavaScript and de-duplicate items - Stack O...

javascript arrays merge
Rectangle 27 30

Here is a slightly different take on the loop. With some of the optimizations in the latest version of Chrome, it is the fastest method for resolving the union of the two arrays (Chrome 38.0.2111).

var array1 = ["Vijendra", "Singh"];
var array2 = ["Singh", "Shakya"];
var array3 = [];

var arr = array1.concat(array2),
  len = arr.length;

while (len--) {
  var itm = arr[len];
  if (array3.indexOf(itm) === -1) {
    array3.unshift(itm);
  }
}

A comment pointed out that one of my setup variables was causing my loop to pull ahead of the rest, because it didn't have to initialize an empty array to write to. I agree with that, so I've rewritten the test to even the playing field, and included an even faster option.

var whileLoopAlt = function(array1, array2) {
    var array3 = [];
    var arr = array1.concat(array2);
    var len = arr.length;
    var assoc = {};

    while(len--) {
        var itm = arr[len];

        if(!assoc[itm]) { // Eliminate the indexOf call
            array3.unshift(itm);
            assoc[itm] = true;
        }
    }

    return array3;
};

In this alternate solution, I've combined one answer's associative array solution to eliminate the .indexOf() call in the loop which was slowing things down a lot with a second loop, and included some of the other optimizations that other users have suggested in their answers as well.

The top answer here with the double loop on every value (i-1) is still significantly slower. lodash is still doing strong, and I still would recommend it to anyone who doesn't mind adding a library to their project. For those who don't want to, my while loop is still a good answer and the filter answer has a very strong showing here, beating out all on my tests with the latest Canary Chrome (44.0.2360) as of this writing.

Check out Mike's answer and Dan Stocker's answer if you want to step it up a notch in speed. Those are by far the fastest of all results after going through almost all of the viable answers.

There's a flaw in your methodology: you put the creation of array3 into the setup phase, while that cost should only be part of your while-based solution's score. With this 1 line moved, your solution falls to the speed of the for loop based one. I understand that array can be reused, but maybe the other algorithms could benefit too from not having to declare and initialize every necessary building block.

I agree with your premise @doldt, but disagree with your results. There is a fundamental design flaw with the loop based removal of entries, in that you have to recheck the length of the array after you have removed items, resulting in a slower execution time. A while loop working backwards does not have these effects. Here is an example with removing as many setup variables as I can without changing their original answer too much: jsperf.com/merge-two-arrays-keeping-only-unique-values/19

@slickplaid the linked tests are empty, and the next revision at jsperf hangs in the while loop.

@slickplaid Thanks for setting up the extended perf page. Unless I'm missing something, the "whileLoopAlt2" function doesn't work? It creates a new array containing the first array, and the second array (in reverse order). To avoid confusion I've made another revision that removes the broken function. I also added an additional example: jsperf.com/merge-two-arrays-keeping-only-unique-values/22

How to merge two arrays in JavaScript and de-duplicate items - Stack O...

javascript arrays merge
Rectangle 27 30

Here is a slightly different take on the loop. With some of the optimizations in the latest version of Chrome, it is the fastest method for resolving the union of the two arrays (Chrome 38.0.2111).

var array1 = ["Vijendra", "Singh"];
var array2 = ["Singh", "Shakya"];
var array3 = [];

var arr = array1.concat(array2),
  len = arr.length;

while (len--) {
  var itm = arr[len];
  if (array3.indexOf(itm) === -1) {
    array3.unshift(itm);
  }
}

A comment pointed out that one of my setup variables was causing my loop to pull ahead of the rest, because it didn't have to initialize an empty array to write to. I agree with that, so I've rewritten the test to even the playing field, and included an even faster option.

var whileLoopAlt = function(array1, array2) {
    var array3 = [];
    var arr = array1.concat(array2);
    var len = arr.length;
    var assoc = {};

    while(len--) {
        var itm = arr[len];

        if(!assoc[itm]) { // Eliminate the indexOf call
            array3.unshift(itm);
            assoc[itm] = true;
        }
    }

    return array3;
};

In this alternate solution, I've combined one answer's associative array solution to eliminate the .indexOf() call in the loop which was slowing things down a lot with a second loop, and included some of the other optimizations that other users have suggested in their answers as well.

The top answer here with the double loop on every value (i-1) is still significantly slower. lodash is still doing strong, and I still would recommend it to anyone who doesn't mind adding a library to their project. For those who don't want to, my while loop is still a good answer and the filter answer has a very strong showing here, beating out all on my tests with the latest Canary Chrome (44.0.2360) as of this writing.

Check out Mike's answer and Dan Stocker's answer if you want to step it up a notch in speed. Those are by far the fastest of all results after going through almost all of the viable answers.

There's a flaw in your methodology: you put the creation of array3 into the setup phase, while that cost should only be part of your while-based solution's score. With this 1 line moved, your solution falls to the speed of the for loop based one. I understand that array can be reused, but maybe the other algorithms could benefit too from not having to declare and initialize every necessary building block.

I agree with your premise @doldt, but disagree with your results. There is a fundamental design flaw with the loop based removal of entries, in that you have to recheck the length of the array after you have removed items, resulting in a slower execution time. A while loop working backwards does not have these effects. Here is an example with removing as many setup variables as I can without changing their original answer too much: jsperf.com/merge-two-arrays-keeping-only-unique-values/19

@slickplaid the linked tests are empty, and the next revision at jsperf hangs in the while loop.

@slickplaid Thanks for setting up the extended perf page. Unless I'm missing something, the "whileLoopAlt2" function doesn't work? It creates a new array containing the first array, and the second array (in reverse order). To avoid confusion I've made another revision that removes the broken function. I also added an additional example: jsperf.com/merge-two-arrays-keeping-only-unique-values/22

How to merge two arrays in JavaScript and de-duplicate items - Stack O...

javascript arrays merge
Rectangle 27 24

The following two are probably a good starting point. lodash also has a customizer function for those special needs!

_.extend
_.merge

Please note that the above methods mutate the original object.

The lodash method worked for me as I wanted to merge two objects and retain properties nested more then one or two levels deep (rather than just replacing/wiping them).

How can I merge properties of two JavaScript objects dynamically? - St...

javascript javascript-objects
Rectangle 27 24

The following two are probably a good starting point. lodash also has a customizer function for those special needs!

_.extend
_.merge

Please note that the above methods mutate the original object.

The lodash method worked for me as I wanted to merge two objects and retain properties nested more then one or two levels deep (rather than just replacing/wiping them).

How can I merge properties of two JavaScript objects dynamically? - St...

javascript javascript-objects
Rectangle 27 14

Just by the way, what you're all doing is overwriting properties, not merging...

This is how JavaScript objects area really merged: Only keys in the to object which are not objects themselves will be overwritten by from. Everything else will be really merged. Of course you can change this behaviour to not overwrite anything which exists like only if to[n] is undefined, etc...:

var realMerge = function (to, from) {

    for (n in from) {

        if (typeof to[n] != 'object') {
            to[n] = from[n];
        } else if (typeof from[n] == 'object') {
            to[n] = realMerge(to[n], from[n]);
        }
    }
    return to;
};
var merged = realMerge(obj1, obj2);

Helped me a lot, the underscore js extend did actually overwrite, instead of merge

Worth noting that typeof array and typeof null will return 'object' and break this.

@Salakar: how would you resolve this?

How can I merge properties of two JavaScript objects dynamically? - St...

javascript javascript-objects