Lodash merge including undefined values

元气小坏坏 提交于 2019-12-08 14:58:43

问题


I'm trying to use Lodash to merge object A into object B, but the trouble I am having is that object A has some undefined values and I want these to be copied over to object B.

Lodash docs for _.merge() says:

"Recursively merges own enumerable properties of the source object(s), that don't resolve to undefined into the destination object."

Is there another function that can do this, or can it be easily overwritten?

EDIT A:

Sample input:

A = {
  name: "Bob Smith",
  job: "Racing Driver",
  address: undefined
}

B = {
  name: "Bob Smith",
  job: "Web Developer",
  address: "1 Regent Street, London",
  phone: "0800 800 80"
}

Expected Output

B = {
  name: "Bob Smith",
  job: "Racing Driver",
  address: undefined,
  phone: "0800 800 80"
}

EDIT B:

Just to confirm, it needs to be a "deep" merge. object may contain nested objects.


回答1:


Easiest would be to use 3rd package for this https://github.com/unclechu/node-deep-extend which goal is only deep merging and nothing else.




回答2:


_.assign/_.extend will do that:

_.assign(B, A);



回答3:


Check this out. It is a small gist containing a deep extend lodash method which you can use within your own application. This will also allow you to get the functionality you need without adding another dependency in your app (since you're already using lodash)




回答4:


Thanks to @Bergi - https://stackoverflow.com/a/22581862/1828637 - assign will keep undefined. I did a customizer here using assignWith for deep merge with customizer, as i use this in redux/react:

function keepUnchangedRefsOnly(objValue, srcValue) {
    if (objValue === undefined) { // do i need this?
        return srcValue;
    } else if (isPlainObject(objValue)) {
        return assignWith({}, objValue, srcValue, keepUnchangedRefsOnly);
    } else if (Array.isArray(objValue)) {
        if (isEmpty(objValue) && !isEmpty(srcValue))return [...srcValue];
        else if (!isEmpty(objValue) && isEmpty(srcValue)) return objValue;
        else if (isEmpty(objValue) && isEmpty(srcValue)) return objValue; // both empty
        else return [ ...objValue, ...srcValue ];
    }
}

Usage like this - https://stackoverflow.com/a/49437903/1828637



来源:https://stackoverflow.com/questions/22581220/lodash-merge-including-undefined-values

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