Skip to content

Instantly share code, notes, and snippets.

@zmts
Created March 7, 2024 15:02
Show Gist options
  • Save zmts/62a2a6f55651b1d9ddb8b1f22d3f6d0b to your computer and use it in GitHub Desktop.
Save zmts/62a2a6f55651b1d9ddb8b1f22d3f6d0b to your computer and use it in GitHub Desktop.
merge objects

Merge objects in JavaScript (lodash)

const mergeWith = require('lodash/mergeWith')
const isArray = require('lodash/isArray')

function mergeObjects(obj1, obj2) {
  return mergeWith(obj1, obj2, (objValue, srcValue) => {
    if (isArray(objValue) && isArray(srcValue)) {
      return objValue.concat(srcValue);
    }
  });
}
const obj1 = { a: {}, b: { c: [1, 2 , 3], f: [] } }
const obj2 = { b: { c: [4, 5 , 6] }, d: null }
console.log(mergeObjects(obj1, obj2))

// >> { a: {}, b: { c: [ 1, 2, 3, 4, 5, 6 ], f: [] }, d: null }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment