0

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?

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.