TehShrike / deepmerge

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

customMerge at lowest level of object #216

Open dsl101 opened 3 years ago

dsl101 commented 3 years ago

I have objects similar to this, and need, for some keys, a custom merge to sum properties:

const thing1 = {
  userId1: {
    shares: 3
  }
}

const thing2 = {
  userId1: {
    shares: 2
  }
}

const sumShares = (s1, s2) => s1 + s2
const opts = {
  customMerge: key => {
    if (key === 'shares') return sumShares
  }
}

const result = merge(thing1, thing2, opts)

But it seems that customMerge() is only called at the userIdX level, not at the lowest level. In reality, the objects are big and complex, but certain keys like this need special handling. Is there a way to call customMerge at every level, not just for object types?

dsl101 commented 3 years ago

BTW—not urgent, as I ended up using merge-lite in the end, which calls the custom merge function at every level, so I could pick out the shares key from there.

RebeccaStevens commented 3 years ago

@TehShrike maybe customMerge should supply more arguments and be of a similar signature to _.mergeWith's customizer function. - This probably isn't needed

I also think it would be a good idea to simply have customMerge be the merge function, ratherthan a function that returns a merge function.

RebeccaStevens commented 3 years ago

@dsl101 If you want customMerge to be called on everything, have isMergeableObject be a function that always returns true. You'll just need to make sure that your custom merge function handles all cases.

dsl101 commented 3 years ago

Yeah—that kind of defeats the purpose though doesn't it? I don't want to handle all cases, just one specifically named key.

RebeccaStevens commented 3 years ago

You could do this:

const opts = {
  isMergeableObject: () => true
  customMerge: key => {
    if (key === 'shares') return sumShares
    return (x, y) => {
      if (myIsMergeableObject(x) && myIsMergeableObject(y)) {
        return merge(x, y, opts)
      }
      return y
    }
  }
}

const result = merge(thing1, thing2, opts)

Where you probably want myIsMergeableObject to be is-plain-object.

mrspok407 commented 3 years ago

@dsl101 Had the same problem. Lodash mergeWith is doing exactly what we need.