Menu

gitpiper

merge javascript Code Snippet in 2024

objectarrayintermediate

Last Updated: 16 December 2024

Creates a new object from the combination of two or more objects.

  • Use Array.prototype.reduce() combined with Object.keys() to iterate over all objects and keys.
  • Use Object.prototype.hasOwnProperty() and Array.prototype.concat() to append values for keys existing in multiple objects.
const merge = (...objs) => [...objs].reduce( (acc, obj) => Object.keys(obj).reduce((a, k) => { acc[k] = acc.hasOwnProperty(k) ? [].concat(acc[k]).concat(obj[k]) : obj[k]; return acc; }, {}), {} );
const object = { a: [{ x: 2 }, { y: 4 }], b: 1 }; const other = { a: { z: 3 }, b: [2, 3], c: 'foo' }; merge(object, other); // { a: [ { x: 2 }, { y: 4 }, { z: 3 } ], b: [ 1, 2, 3 ], c: 'foo' }

javascript snippet similar to merge For You in December 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! ✌️