Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

customMerge at lowest level of object #216

Open
dsl101 opened this issue Nov 13, 2020 · 6 comments
Open

customMerge at lowest level of object #216

dsl101 opened this issue Nov 13, 2020 · 6 comments

Comments

@dsl101
Copy link

dsl101 commented Nov 13, 2020

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
Copy link
Author

dsl101 commented Nov 13, 2020

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
Copy link

RebeccaStevens commented Nov 17, 2020

@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
Copy link

@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
Copy link
Author

dsl101 commented Nov 28, 2020

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
Copy link

RebeccaStevens commented Nov 28, 2020

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
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants