How to merge array of objects using lodash

亡梦爱人 提交于 2020-01-22 02:26:32

问题


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:


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>


来源:https://stackoverflow.com/questions/58452824/how-to-merge-array-of-objects-using-lodash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!