Travis build: 1213
This commit is contained in:
41
README.md
41
README.md
@ -266,6 +266,7 @@ average(1, 2, 3);
|
||||
* [`lowercaseKeys`](#lowercasekeys)
|
||||
* [`mapKeys`](#mapkeys)
|
||||
* [`mapValues`](#mapvalues)
|
||||
* [`merge`](#merge)
|
||||
* [`objectFromPairs`](#objectfrompairs)
|
||||
* [`objectToPairs`](#objecttopairs)
|
||||
* [`orderBy`](#orderby)
|
||||
@ -4071,6 +4072,46 @@ mapValues(users, u => u.age); // { fred: 40, pebbles: 1 }
|
||||
<br>[⬆ Back to top](#table-of-contents)
|
||||
|
||||
|
||||
### 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;
|
||||
}, {}),
|
||||
{}
|
||||
);
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```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' }
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#table-of-contents)
|
||||
|
||||
|
||||
### objectFromPairs
|
||||
|
||||
Creates an object from the given key-value pairs.
|
||||
|
||||
File diff suppressed because one or more lines are too long
@ -10,9 +10,7 @@ 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;
|
||||
}, {}),
|
||||
{}
|
||||
@ -22,12 +20,12 @@ const merge = (...objs) =>
|
||||
```js
|
||||
const object = {
|
||||
a: [{ x: 2 }, { y: 4 }],
|
||||
b: 1,
|
||||
b: 1
|
||||
};
|
||||
const other = {
|
||||
a: { z: 3 },
|
||||
b: [2, 3],
|
||||
c: 'foo',
|
||||
c: 'foo'
|
||||
};
|
||||
merge(object, other); // { a: [ { x: 2 }, { y: 4 }, { z: 3 } ], b: [ 1, 2, 3 ], c: 'foo' }
|
||||
```
|
||||
|
||||
Reference in New Issue
Block a user