Varun Sridharan
Varun Sridharan

Reputation: 1978

Merge 2 sets of Object + Array Using Javascript

I am trying to merge 2 sets of Object & Array like below

{
  exclude: ['placeholder'],
  attributes: { MYID : '' }
  map: 'input'
}

AND

{
 exclude: ['options'],
 attributes: { class: '', id:'', name:'', },
 map: '',
}

I tried using jQuery's $.extend function it worked but it only merge objects. And also tried with lodash js which also dose not work. I get output as

{
  exclude: ['options'],
  attributes: { class: '', id: '', name: '', MYID: '' },
  map: '',
}

I need output like

{
  exclude: ['options','placeholder'],
  attributes: { class: '', id: '', name: '', MYID: '' },
  map: '',
}

Code I tried using

$.extend(true,{
  exclude: ['placeholder'],
  attributes: { MYID : '' }
  map: 'input'
},{
 exclude: ['options'],
 attributes: { class: '', id:'', name:'', },
 map: '',
});

Upvotes: 1

Views: 83

Answers (2)

Artem
Artem

Reputation: 2047

Because _.extend(...) overrides existing fields instead of fill it.

Try using _.mergeWith(,, customizer) with customizer function, that is responsible for merging fields the way is needed, like:

function customizer(initialObject, source) {
    if (_.isArray(initialObject)) {
        return initialObject.concat(source);
    } else if (_.isObject(initialObject)) {
        return _.extend(initialObject, source);
    } else {
        return source;
    }
}

_.mergeWith({a: [1], b: {c: 4}}, {a: [2, 3], b: {d: 5}}, customizer);

//{a: Array(3), b: {…}}
//a
//:
//(3) [1, 2, 3]
//b
//:
//{c: 4, d: 5}
//__proto__
//:
//Object

Upvotes: 1

Nenad Vracar
Nenad Vracar

Reputation: 122145

You can create custom function for this using for...in loop and check type of each value.

var obj1 = {
  exclude: ['placeholder'],
  attributes: { MYID : '' },
  map: 'input'
}

var obj2 = {
 exclude: ['options'],
 attributes: { class: '', id:'', name:'', },
 map: '',
}


function merge(o1, o2) {
  for (var i in o2) {
    if (o1[i]) {
      if (typeof o2[i] == 'object') {
        if (Array.isArray(o2[i])) o1[i].push(...o2[i])
        else o1[i] = Object.assign({}, o1[i], o2[i])
      } else {
      	 o1[i] = o2[i]
      }
    } else {
      o1[i] = o2[i]
    }
  }
  return o1;
}


console.log(merge(obj1, obj2))

Upvotes: 2

Related Questions