Home > database >  merging 2 nested object in javascript react
merging 2 nested object in javascript react

Time:08-24

const obj1 = {
    prop1: 'value1',
    prop2: 'value2',
    prop3: { prop4: 'value4', prop5: {
         prop5: 'value5'
         } 
    },
}
const obj2 = {
    prop6: 'value6',
    prop2: 'value2',
    prop7: { prop8: 'value8', prop9: {
         prop10: 'value10'
         } 
    },
}

so i have this two very nested object in javascript and i want to merge is to be just one object. some of the object property is identical but some are not, i want to merge it so the identical ones stay. how do i merge this two deeply nested object?

CodePudding user response:

You can try this:

const obj1 = {
    prop1: 'value1',
    prop2: 'value2',
    prop3: { prop4: 'value4', prop5: {
         prop5: 'value5'
         } 
    },
}
const obj2 = {
    prop6: 'value6',
    prop2: 'value2',
    prop7: { prop8: 'value8', prop9: {
         prop10: 'value10'
         } 
    },
}

const merged = {...obj1, ...obj2}

console.log(merged)

CodePudding user response:

Recursive merge for array and object

const obj1 = {
  prop1: 'value1',
  prop2: 'value2',
  prop3: {
    prop4: 'value4',
    prop5: {
      prop5: 'value5'
    },
    a: ['a', 'b']
  },
}

const obj2 = {
  prop6: 'value6',
  prop2: 'value2',
  prop7: {
    prop8: 'value8',
    prop9: {
      prop10: 'value10'
    }
  },
  prop3: {
    prop9: 'value9',
    prop8: {
      prop7: 'value7',
      prop8: {
        prop7: 'value7'
      }
    },
    a: ['a', 'b']
  },
}


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(obj1, obj2)

console.log(result)

  • Related