Menu

gitpiper

deepMerge javascript Code Snippet in 2024

objectfunctionadvanced

Last Updated: 24 March 2024

Deeply merges two objects, using a function to handle keys present in both.

  • Use Object.keys() to get the keys of both objects, create a Set from them and use the spread operator (...) to create an array of all the unique keys.
  • Use Array.prototype.reduce() to add each unique key to the object, using fn to combine the values of the two given objects.
const deepMerge = (a, b, fn) => [...new Set([...Object.keys(a), ...Object.keys(b)])].reduce( (acc, key) => ({ ...acc, [key]: fn(key, a[key], b[key]) }), {} );
deepMerge( { a: true, b: { c: [1, 2, 3] } }, { a: false, b: { d: [1, 2, 3] } }, (key, a, b) => (key === 'a' ? a && b : Object.assign({}, a, b)) ); // { a: false, b: { c: [ 1, 2, 3 ], d: [ 1, 2, 3 ] } }

javascript snippet similar to deepMerge For You in March 2024

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2024 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️