TehShrike / deepmerge

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

Feature Request: Passing a collision callback for colliding props #262

Open jorenbroekema opened 8 months ago

jorenbroekema commented 8 months ago

It would be quite useful to be able to take certain action (such as debug logging) when deepmerging objects that causes properties to collide with one another.

Example:

const obj1 = {
  foo: "foo",
  bar: "bar",
  qux: {
    1: true,
    "hello": "world"
  }
}

const obj2 = {
  foo: "otherFoo", // collision w obj1
  bar: "bar",
  qux: {
    2: false,
    "hello": "planet" // collision w obj1
  }
}

const objMerged = deepmerge(obj1, obj2, { 
  onCollision: ({ target, destination, key, values, path }) => {
    // target = obj1, destination = obj2
    console.log(`Collision found for prop ${key} -> value: ${values[1]} takes precedence over value: ${values[0]}. Path to prop: ${path.join('.')}`);
  }
});

Console output:

Collision found for prop foo -> value: otherFoo takes precedence over value: foo. Path to prop: foo
Collision found for prop hello -> value: planet takes precedence over value: world. Path to prop: qux.hello

callback API is just a first idea for what meta data is useful to pass to a collision function.

I haven't really thought through how this would work fo: functions & other non-plain objects, but for Arrays I suppose it doesn't make that much sense, because they always collide and need to be merged in some way e.g. by concating them. So perhaps a better name is onPropCollision if it only makes sense for object properties.

I'm willing to create a PR for this, just let me know (maintainer(s))