如何使用lodash合并对象数组 [英] How to merge array of objects using lodash

查看:1291
本文介绍了如何使用lodash合并对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用自定义函数将一个数组中的所有对象合并为一个对象.使用lodash的mergeWith效果很好:

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]}

这很好用,但为该副本创建数组副本(a.slice(1))似乎很浪费-还有另一种方法将该数组传递给mergeWith吗?

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?

推荐答案

您的代码实际上是对a[0]进行了突变.但是,如果要突变第一个元素,只需扩展a就足够了mergeWith(...a, fn):

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>

如果不想变异数组的第一个元素,请传播到新对象mergeWith({}, ...a, fn):

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>

这篇关于如何使用lodash合并对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆