From c1be98605159f99cac5e16f787cf139ab8a04e24 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Fri, 12 Jan 2018 14:44:20 +0200 Subject: [PATCH] Add merge --- snippets/merge.md | 33 +++++++++++++++++++++++++++++++++ tag_database | 1 + 2 files changed, 34 insertions(+) create mode 100644 snippets/merge.md diff --git a/snippets/merge.md b/snippets/merge.md new file mode 100644 index 000000000..fbc4ec7b7 --- /dev/null +++ b/snippets/merge.md @@ -0,0 +1,33 @@ +### merge + +Creates a new object from the combination of two or more objects. + +Use `Array.reduce()` combined with `Object.keys(obj)` to iterate over all objects and keys. +Use `hasOwnProperty()` and `Array.concat()` to append values for keys existing in multiple objects. + +```js +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; + }, {}), + {} + ); +``` + +```js +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' } +``` diff --git a/tag_database b/tag_database index e70eef4a2..e1d4aa6aa 100644 --- a/tag_database +++ b/tag_database @@ -112,6 +112,7 @@ maxBy:math,array,function maxN:array,math median:math,array memoize:function +merge:object,array minBy:math,array,function minN:array,amth negate:function