(_.merge in ES6/ES7)Object.assign without overriding undefined values

There is _.merge functionality in lodash. I want to achieve the same thing in ES6 or ES7.

Having this snippet:

Object.assign({}, {key: 2}, {key: undefined})

I want to receive {key: 2}. Currently I receive {key: undefined}

This is NOT a deep merge.

Is it possible? If yes then how to achieve that?



You can't achieve that with a straight usage of Object.assign, because each next object will rewrite the same keys for prev merge. The only way, to filter your incoming objects with some hand-crafted function.

function filterObject(obj) {
    const ret = {};
        .filter((key) => obj[key] !== undefined)
        .forEach((key) => ret[key] = obj[key]);
    return ret;

You can simply filter out the keys with undefined values before passing them to Object.assign():

const assign = (target, ...sources) =>
  Object.assign(target, ...sources.map(x =>
      .filter(([key, value]) => value !== undefined)
      .reduce((obj, [key, value]) => (obj[key] = value, obj), {})

console.log(assign({}, {key: 2}, {key: undefined}))


Write a little utility to remove undefined values:

function removeUndefined(obj) {
  for (let k in obj) if (obj[k] === undefined) delete obj[k];
  return obj;


Object.assign({}, {key: 2}, removeUndefined({key: undefined}))

This seems preferable to writing your own assign with wired-in behavior to remove undefined values.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.