Search code examples
javascriptangulartypescriptecmascript-6lodash

I have two objects and i need to merge them and concat strings if two props have the same key


I have two objects and i need to merge them and concat strings if two props have the same key note: I'm using lodash.js

obj1 = {
  name: 'john', 
  address: 'cairo'
}

obj2 = {
  num : '1', 
  address: 'egypt'
}

I need the merged object to be like:

merged = {name:"john", num: "1", address:"cairo,Egypt"}

the issue with address prop when I'm trying to use _.defaults(obj1,obj2) or _.merge(obj1,obj2)

the address value will be the value of the address prop inside obj2 so I need a way to merge the two objects and concat the two address props in each object.


Solution

  • Try this:

        function merge(obj1, obj2) {
          let merged = {
            ...obj1,
            ...obj2
          };
          Object.keys(obj1).filter(k => obj2.hasOwnProperty(k)).forEach((k) => {
            merged[k] = obj1[k] + "," + obj2[k]
          })
          return merged
        }
    
        obj1 = {
          name: 'john',
          address: 'cairo'
        }
    
        obj2 = {
          num: '1',
          address: 'egypt'
        }
    
        console.log(merge(obj1, obj2))