Merge objects updating keys

53 Views Asked by At

Lets say I have two objects, for example

const obj1 = {
a: [{asd1: 1}, {asd2: 2}, {asd3: 3}]
}

const obj2 = {
a: [{asd4: 4}],
b: [{a: "asd"}, {b: "asd"}]
}

I have to merge the two objects having a result like this

obj3 = {
a: [{asd1: 1}, {asd2: 2}, {asd3: 3}, {asd4: 4}]
b: [{a: "asd"}, {b: "asd"}]
}

What would be the most effective way to accomplish this?

3

There are 3 best solutions below

0
IT goldman On BEST ANSWER

What if a property is an object in both objects? Then a recursion is in place.

function mergeObjects(obj1, obj2) {
  const obj3 = {};

  for (var key in obj1) {

    if (Array.isArray(obj1[key]) && Array.isArray(obj2[key])) {
      obj3[key] = obj1[key].concat(obj2[key]);
    } else if (typeof obj1[key] === 'object' && typeof obj2[key] === 'object') {
      obj3[key] = mergeObjects(obj1[key], obj2[key]);
    } else {
      obj3[key] = obj1[key];
    }

  }

  for (var key in obj2) {
    if (!obj3.hasOwnProperty(key)) {
      obj3[key] = obj2[key];
    }
  }

  return obj3;
}

const obj1 = {
  a: [{
    asd1: 1
  }, {
    asd2: 2
  }, {
    asd3: 3
  }],
  c: {
    a: [1]
  }
};

const obj2 = {
  a: [{
    asd4: 4
  }],
  b: [{
    a: "asd"
  }, {
    b: "asd"
  }],
  c: {
    a: [2]
  }
};

const obj3 = mergeObjects(obj1, obj2);
console.log(obj3);
.as-console-wrapper {
  min-height: 100% !important
}

0
flyingfox On

Here is a reference for you,but not elegant,waiting to see others answer

const obj1 = {
a: [{asd1: 1}, {asd2: 2}, {asd3: 3}]
}

const obj2 = {
a: [{asd4: 4}],
b: [{a: "asd"}, {b: "asd"}]
}

let keys = new Set(Object.keys(obj1).concat(Object.keys(obj2)))

let obj3 = {}
for(k of keys){
  let v1 = obj1[k] || []
  let v2 = obj2[k] || []
  obj3[k] = v1.concat(v2)
}
console.log(obj3)

0
Lã Ngọc Hải On

In case your objects' properties has consistent type: just use spread syntax (coelesce to an empty array if the property can be undefined)

const obj1 = {
  a: [{asd1: 1}, {asd2: 2}, {asd3: 3}]
}

const obj2 = {
  a: [{asd4: 4}],
  b: [{a: "asd"}, {b: "asd"}]
}
const obj3 = {
  a:[...obj1.a??[],...obj2.a??[]],
  b:[...obj1.b??[],...obj2.b??[]]
}
console.log(obj3)