deepmerge icon indicating copy to clipboard operation
deepmerge copied to clipboard

Fix merging with empty values

Open johnlife opened this issue 5 years ago • 7 comments

Adds isEmpty option. Then the following code

const newObject = {
  foo: {
    one: null,
    two: "New text",
    three: ""
  }
}

const defaultObject = {
  foo: {
    one: "Some default text",
    two: "Some other default text",
    three: "Even more default text"
  }
}

const mergedObject = deepmerge(defaultObject, newObject, {
  isEmpty: a => a === null || a === '',
});
console.log(mergedObject);

gives you

{ 
  foo: { 
    one: 'Some default text',
     two: 'New text',
     three: 'Even more default text' 
  } 
}

johnlife avatar Dec 22 '19 03:12 johnlife

This is way too specialized/specific. It's fine as a fork to use in a specific project, but isn't a good feature for a broadly-used utility.

I am open to changing the customMerge function signature to make it easy to solve for your use case without having to modify the code, though.

TehShrike avatar Dec 23 '19 02:12 TehShrike

@TehShrike I need this too! So I basically want to merge only when the new object has a value (avoiding nulls overriding). Something like here:

https://www.rubydoc.info/gems/deep_merge/1.2.1

:merge_nil_values       DEFAULT: false
  Set to true to merge nil hash values, overwriting a possibly non-nil value

This does not seem to be possible to do using customMerge function? However, it seems to be quite common case, so I would really welcome a new merge option

mergeNilValues DEFAUL: true

This would not break existing behavior but would allow to turn it off.

pkuczynski avatar Jan 10 '20 16:01 pkuczynski

I have the same use case to ignore empty strings when merging. I think it would make sense to extend the signature of customMerge to provide values, so this and similar use cases could easily be solved. This would make this package a lot more flexible, in my opinion.

n0v1 avatar Apr 28 '20 08:04 n0v1

I would love to have this as well.

panec avatar Jun 05 '20 10:06 panec

+1 To the modification to customMerge signature. Allows users to implement multiple edge cases.

davidatkinsondoyle avatar Aug 18 '20 14:08 davidatkinsondoyle

+1 here need some way of handling this

TheHaff avatar Oct 05 '20 16:10 TheHaff

My previous comment stands – I'm open to PRs to make the necessary changes to customMerge to enable this.

TehShrike avatar Oct 05 '20 21:10 TehShrike