skip to Main Content

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?

2

Answers


  1. 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)
    Login or Signup to reply.
  2. 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
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search