Reputation: 2105
I would like to merge all objects in one array into one object, with a custom function. Using lodash's mergeWith
works well:
let a = [{a: [1,2]}, {a:[3,4]}, {a: [7,8]}]
let b = mergeWith(
a[0],
...a.slice(1),
(objValue: any, srcValue: any) => {
if (Array.isArray(objValue)) {
return objValue.concat(srcValue);
}
},
);
console.log(b);
// result: {a:[1,2,3,4,7,8]}
This works fine but it seems wasteful to create an array copy just for that (a.slice(1)
) - is there another way to pass that array to mergeWith
?
Upvotes: 0
Views: 967
Reputation: 192477
Your code actually mutates a[0]
. However, if you want to mutate the 1st element, just spreading a
would be enough mergeWith(...a, fn)
:
let a = [{a: [1,2]}, {a:[3,4]}, {a: [7,8]}]
let b = _.mergeWith(
...a,
(objValue, srcValue) => _.isArray(objValue) ? objValue.concat(srcValue) : undefined,
);
console.log(b); // result: {a:[1,2,3,4,7,8]}
console.log(a[0]); // result: {a:[1,2,3,4,7,8]}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
If you don't want to mutate the 1st element of the array, spread into a new object mergeWith({}, ...a, fn)
:
let a = [{a: [1,2]}, {a:[3,4]}, {a: [7,8]}]
let b = _.mergeWith(
{}, // new object
...a,
(objValue, srcValue) => _.isArray(objValue) ? objValue.concat(srcValue) : undefined,
);
console.log(b); // result: {a:[1,2,3,4,7,8]}
console.log(a[0]); // result: {a:[1,2]}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
Upvotes: 1