Update snippet descriptions

This commit is contained in:
Isabelle Viktoria Maciohsek
2020-10-21 21:54:53 +03:00
parent 47276ac092
commit ce48fffb4d
41 changed files with 171 additions and 110 deletions

View File

@ -5,15 +5,17 @@ tags: object,array,intermediate
Creates a new object from the combination of two or more objects.
- Use `Array.prototype.reduce()` combined with `Object.keys(obj)` to iterate over all objects and keys.
- Use `hasOwnProperty()` and `Array.prototype.concat()` to append values for keys existing in multiple 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.
```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];
acc[k] = acc.hasOwnProperty(k)
? [].concat(acc[k]).concat(obj[k])
: obj[k];
return acc;
}, {}),
{}
@ -30,5 +32,6 @@ const other = {
b: [2, 3],
c: 'foo'
};
merge(object, other); // { a: [ { x: 2 }, { y: 4 }, { z: 3 } ], b: [ 1, 2, 3 ], c: 'foo' }
```
merge(object, other);
// { a: [ { x: 2 }, { y: 4 }, { z: 3 } ], b: [ 1, 2, 3 ], c: 'foo' }
```