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

Question: Any way to customize merge to "replace" arrays? #559

Open
is-jonreeves opened this issue Sep 19, 2024 · 1 comment
Open

Question: Any way to customize merge to "replace" arrays? #559

is-jonreeves opened this issue Sep 19, 2024 · 1 comment

Comments

@is-jonreeves
Copy link

We often need to merge deep options where there is usually a base/initial set of defaults that are then overridden by the input. I think this is a pretty common usecase for property-sheets/configurations.

Historically we've had lodash handy and have leaned on lodash.merge for that, but we started trying to move away from it. Recently we went tested out a whole collection of different util libs including radash, but found the merge functionality in most of them to be different to what "we" expected. We ended up choosing to use deepmerge-ts for this specific function in the end (as it was customizable).

I just stumbled across es-toolkit and played with your merge function, I noted that when merging arrays the strategy seems to be index replacement. Is there anyway to change/customize this? In the usecase described above, typically the expectation would be whole array replacement when present, skip when undefined.

If not, is this something you would consider adding, or is there perhaps another more appropriate function that I might have overlooked?

@raon0211
Copy link
Collaborator

Does mergeWith serve your needs? It can customize the merge behavior to concat two arrays.

const target = { a: [1], b: [2] };
const source = { a: [3], b: [4] };

mergeWith(target, source, (objValue, srcValue) => {
  if (Array.isArray(objValue)) {
    return objValue.concat(srcValue);
  }
});
// Returns { a: [1, 3], b: [2, 4] })

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

2 participants