skip to Main Content

I have two objects. I need to merge them using JavaScript.

let object1 = {
  fruits :[apple, orange],
  veggies:[carrot, pumpkin],
}

let object2 = {
  fruits :[apple, banana, mango],
  veggies:[potato, brinjal]
}


Expected output:

let object3 = {
  fruits : [apple,orange,banana,mango],
  veggies:[carrot,pumpkin,potato,brinjal]
}

Things I tried:

  1. object3 = {...object1, ...object2}
  2. const object3 = (obj1, obj2) => Object.assign({}, ...Object.keys(obj1).map(i => ({[i]:{...obj1[i], ...obj2[i]}}))); console.log(object3(object1, object2));

3

Answers


  1. Your 2 tries didn’t work because:

    1. This only merge the destructed objects, it doesn’t merge the values inside
    2. This is getting closer, but it doesn’t do the merge logic

    Try this:

    let object1 = {
      fruits :['apple', 'orange'],
      veggies:['carrot', 'pumpkin'],
    }
    
    let object2 = {
      fruits :['apple', 'banana', 'mango'],
      veggies:['potato', 'brinjal']
    }
    
    function mergeObj(...objs) {
      const keys = objs.map(o => Object.keys(o)).flat();
      return keys.reduce((result, key) => {
        result[key] = [...new Set(objs.map(o => o[key]).flat())];
        return result;
      }, {});
    }
    
    console.log(mergeObj(object1, object2))
    
    Login or Signup to reply.
  2. here’s my code

     let object1 = {
      fruits :['apple', 'orange'],
       veggies:['carrot', 'pumpkin'],
     }
    
      let object2 = {
        fruits :['apple', 'banana', 'mango'],
       veggies:['potato', 'brinjal']
     }
    
    
    
     const Merge = (object1, object2) => {
     if (Array.isArray(object2)) {
        return [...object1, ...object2]
        } else {
        return Object.entries(object2).reduce((acc, [key, value]) => {
          if (
           Object.keys(acc).includes(key) &&
           typeof value === 'object'
          ) {
           acc[key] = Merge(acc[key], value)
          } else {
           acc[key] = value
          }
      
          return acc
        }, { ...object1 })
       }
     }
    
     const result = Merge(object1, object2);
    
     console.log(result);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search