Abhineet Sinha
Abhineet Sinha

Reputation: 105

How to add values to an object property from another object having the same definition In JavaScript

I have an object similar to the one below:

var obj1 = {
  fparams: {
    keys: ['a', 'b'],
    pairs: {
      'p': 'qwert'
    }
  },
  qparams: {
    'x': 'xyz'
  }
}

And another one as:

var obj2 = {
  fparams: {
    keys: ['c', 'd'],
    pairs: {
      'q': 'yuiop'
    }
  },
  qparams: {
    'z': 'zyx'
  }
}

What can I do to add the properties from obj2 object to obj1?

As I am working in Angular, I tried to use angular.merge(obj1,obj2) but it does not merge the keys array, but overwrites it with the keys value from obj2, rest of the properties get merged though.

Here's what I want in the end:

var obj2 = {
  fparams: {
    keys: ['a', 'b', 'c', 'd'],
    pairs: {
      'p': 'qwert',
      'q': 'yuiop'
    }
  },
  qparams: {
    'x': 'xyz',
    'y': 'zyx'
  }
}

Also The angular Version I'm Using Is angular 1.5.8

Edit : Ended up using lodash , as it was much easier to work with and tons of functionalities which I was not previously aware of.

Upvotes: 4

Views: 1215

Answers (4)

Redu
Redu

Reputation: 26161

I guess simply with pure JS and the help of the recursive function mergeObjects you can do as follows;

function mergeObjects(o1,o2){
  return Object.keys(o1)
               .reduce(function(r,k){
                         o1[k] = Array.isArray(o1[k]) ? o1[k].concat(o2[k])
                                                      : typeof o1[k] === "object" ? mergeObjects(o1[k],o2[k])
                                                                                  : (r = Object.assign({},o1,o2),o1[k]);
                         return r;
                       }, o1);
}

var objs = [{
             fparams: {
                       keys : ['a', 'b'],
                       pairs: {
                               'p': 'qwert'
                              }
                      },
             qparams: {
                       'x': 'xyz'
                      }
            },
            {
             fparams: {
                       keys : ['c', 'd'],
                       pairs: {
                               'q': 'yuiop'
                              }
                       },
             qparams: {
                       'z': 'zyx'
                      }
            }],
  result = objs.reduce(mergeObjects);
console.log(JSON.stringify(result,null,2));

Upvotes: 1

S4beR
S4beR

Reputation: 1847

try this function, I have tried to cover most of the scenarios though it might not be as good as other libraries available

var merge = function(obj1, obj2) {

  for (var key in obj2) {
    if (obj2.hasOwnProperty(key)) {
       if (obj1[key] == null) {
           obj1[key] = obj2[key];
       } else if (obj1[key] instanceof Array) {
           if (obj2[key] instanceof Array) {
               for (var i =0; i < obj2[key].length; i++){
                   if (obj1[key].indexOf(obj2[key]) === -1) {
                       obj1[key].push(obj2[key][i]);
                   }
               }
           }
       } else if (obj1[key] instanceof Object && obj2[key] instanceof Object && obj1[key].constructor == Object && obj2[key] == Object) {
           merge(obj1[key], obj2[key]);
       }
    }
  }
}

You can use it as below

merge(obj1, obj2);

Upvotes: 0

Nenad Vracar
Nenad Vracar

Reputation: 122057

With lodash you can use mergeWith and create desired result, so when value is array you need to concat values.

var obj1 = {"fparams":{"keys":["a","b"],"pairs":{"p":"qwert"}},"qparams":{"x":"xyz"}}
var obj2 = {"fparams":{"keys":["c","d"],"pairs":{"q":"yuiop"}},"qparams":{"z":"zyx"}}

var result = _.mergeWith(obj1, obj2, function(a, b) {
  if(_.isArray(a)) return a.concat(b)
})

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

Here is my attempt at deep merge, using recursion, not sure if it will work on all data structures.

var obj1 = {"fparams":{"keys":["a","b"],"pairs":{"p":"qwert"}},"qparams":{"x":"xyz"}}
var obj2 = {"fparams":{"keys":["c","d"],"pairs":{"q":"yuiop"}},"qparams":{"z":"zyx"}}

function merge(o1, o2) {
  var result = {}
  for (var i in o1) {
    for (var j in o2) {
      if (i == j && typeof o1[i] == 'object' && typeof o2[j] == 'object') {
        if (Array.isArray(o1[i]) || Array.isArray(o2[j])) {
          result[i] = Array.isArray(o1[i]) ? o1[i].concat(o2[j]) : o2[j].concat(o1[i])
        } else {
          result[i] = Object.assign(result[i] || {}, merge(o1[i], o2[j]))
        }
      }
      if (typeof o1[i] != 'object' || typeof o2[j] != 'object') {
        result[i] = o1[i]
        result[j] = o2[j]
      }

    }
  }
  return result;
}

console.log(JSON.stringify(merge(obj1, obj2), 0, 4))

Upvotes: 1

brunobastosg
brunobastosg

Reputation: 1426

Did you consider using Lodash? It has a merge method that does exactly that.

Upvotes: 3

Related Questions