TehShrike / deepmerge

A library for deep (recursive) merging of Javascript objects
MIT License
2.75k stars 216 forks source link

Fix merging with empty values #185

Open johnlife opened 4 years ago

johnlife commented 4 years ago

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' 
  } 
}
TehShrike commented 4 years ago

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.

pkuczynski commented 4 years ago

@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.

n0v1 commented 4 years ago

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.

panec commented 4 years ago

I would love to have this as well.

davidatkinsondoyle commented 4 years ago

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

TheHaff commented 3 years ago

+1 here need some way of handling this

TehShrike commented 3 years ago

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