I have an array of objects which looks like this:
const childrens = [
{ orderName: "#1004" },
{ orderName: "#1006" },
{ orderName: "#1007" },
{ orderName: "#1005" },
{ deliveryDate: "25-25-25" },
{ signature: "xq" },
];
I want this to be converted into object and have values of same keys as an array of values like this
{
orderName: [ '#1004', '#1006', '#1007', '#1005' ],
deliveryDate: [ '25-25-25' ],
signature: [ 'xq' ]
}
The way i'm doing this right now is by using a reduce function like this
_.reduce(
childrens,
(acc, cur) => {
const pairs = _.chain(cur).toPairs().flatten().value();
if (acc[pairs[0]] === undefined) {
acc[pairs[0]] = [pairs[1]];
} else {
acc[pairs[0]].push(pairs[1]);
}
return acc;
},
{},
);
I'm wondering if there's a cleaner way using built-in lodash functions?
You can use _.mergeWith()
with array spread. When merging 2 values, check if the 1st (a
) is still undefined
(the empty object), if so return the 2nd item wrapped in an array, if it exists, use array spread to concat them:
const children = [{"orderName":"#1004"},{"orderName":"#1006"},{"orderName":"#1007"},{"orderName":"#1005"},{"deliveryDate":"25-25-25"},{"signature":"xq"}];
const result = _.mergeWith({}, ...children, (a, b) =>
_.isUndefined(a) ? [b] : [...a, b]
);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>