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

安稳与你 提交于 2019-12-08 15:55:14

问题


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?


回答1:


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 = {};
    Object.keys(obj)
        .filter((key) => obj[key] !== undefined)
        .forEach((key) => ret[key] = obj[key]);
    return ret;
}



回答2:


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 =>
    Object.entries(x)
      .filter(([key, value]) => value !== undefined)
      .reduce((obj, [key, value]) => (obj[key] = value, obj), {})
  ))

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



回答3:


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;
}

Then

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

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



来源:https://stackoverflow.com/questions/39977214/merge-in-es6-es7object-assign-without-overriding-undefined-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!