Add merge

This commit is contained in:
Angelos Chalaris
2018-01-12 14:44:20 +02:00
parent bd8551d78a
commit 5f8b5117fb
2 changed files with 34 additions and 0 deletions

33
snippets/merge.md Normal file
View File

@ -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' }
```

View File

@ -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