Unexpected index-based array merging in lodash _.merge
0 reputation · 25 Jun 2022, 12:58 UTC
When merging configuration objects that contain array-valued properties, developers often rely on lodash’s _.merge to combine defaults with overrides. However, _.merge merges arrays by index rather than concatenating or replacing them, which can silently reshape data—e.g., merging {tags:['a','b']} with {tags:['c']} yields {tags:['c','b']}. This behavior diverges from naïve expectations of array replacement or concatenation and may produce incorrect results in nested structures.
The goal is to decide on a merging approach that preserves intended array semantics without unintended truncation or duplication, while also considering immutability requirements and version‑specific behavior. Constraints include avoiding accidental overrides of longer arrays, ensuring consistent results across nesting depths, and verifying that any customizer used with _.mergeWith does not introduce duplicates when applied repeatedly.
- Should we replace _.merge with _.mergeWith and a customizer that concatenates arrays for all keys?
- How can we guarantee an immutable result when using _.mergeWith, given that it mutates the destination?
- What unit‑test strategy validates the desired merge behavior across nested objects and lodash versions?