Add merge
This commit is contained in:
33
snippets/merge.md
Normal file
33
snippets/merge.md
Normal 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' }
|
||||||
|
```
|
||||||
@ -112,6 +112,7 @@ maxBy:math,array,function
|
|||||||
maxN:array,math
|
maxN:array,math
|
||||||
median:math,array
|
median:math,array
|
||||||
memoize:function
|
memoize:function
|
||||||
|
merge:object,array
|
||||||
minBy:math,array,function
|
minBy:math,array,function
|
||||||
minN:array,amth
|
minN:array,amth
|
||||||
negate:function
|
negate:function
|
||||||
|
|||||||
Reference in New Issue
Block a user