Search code examples
javascriptjqueryunderscore.jslodash

How to concatenate two object with array properties in JavaScript?


I have two objects:

var one = {
  addedItems: [0, 1],
  removedItems: [8, 9],
  oneTwo: false,
  someStuff: {
    anotherArray: ['a', 'b']
  }
};

var two = {
  addedItems: [3, 4],
  removedItems: [6, 7],
  someStuff: {
    anotherArray: ['c', 'd']
  }
};

And in the end I need to merge these two objects and get something like this:

{
  addedItems: [0, 1, 3, 4],
  removedItems: [8, 9, 6, 7],
  oneTwo: false,
  someStuff: {
    anotherArray: ['a', 'b', 'c', 'd']
  }
}

The operation should be performed on objects with different structure.

What is the best way (or just possible way) to do this? Are there any methods in jQuery or underscore/lodash that allow to do this?


Solution

  • You could generate a new object and append arrays with the items from the already inserted array.

    function deepMerge(source, target) {
        Object.keys(source).forEach(function (k) {
            if (Array.isArray(source[k])) {
                if (!Array.isArray(target[k])) {
                    target[k] = [];
                }          
                target[k] = target[k].concat(source[k]);
                return;
            }
            if (source[k] && typeof source[k] === 'object') {
                target[k] = target[k] || {};
                deepMerge(source[k], target[k]);
                return;
            }
            target[k] = source[k];
        });
    }
    
    var one = { addedItems: [0, 1], removedItems: [8, 9], oneTwo: false, someStuff: { anotherArray: ['a', 'b'] } },
        two = { addedItems: [3, 4], removedItems: [6, 7], someStuff: { anotherArray: ['c', 'd'] } },
        result = {};
    
    deepMerge(one, result);
    deepMerge(two, result);
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }