如何合并对象数组中的对象? [英] How can you merge objects in array of objects?

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

问题描述

我正在寻找将所有对象合并到一个数组中的最佳解决方案

I'm looking for the best solution to merge all objects in one array

const arrayOfObjects = [
 {name: 'Fred', surname: 'Shultz'}, {name: 'Anne', surname: 'Example'}
];

我想要实现:{name: ['Fred', 'Anne'], surname: ['Example', 'Shultz']}

该(es6)的最佳选择是什么?也许我可以使用lodash做类似的事情?我应该使用哪些助手?

What's the best option for that (es6)? Maybe I can do something like that using lodash? Which helpers should I use?

推荐答案

您可以使用lodash的 mergeWith 这样:

You can use lodash's mergeWith like so:

const result = _.mergeWith({}, ...arrayOfObjects, (value, objValue) =>
    (value || []).concat(objValue)
);

示例:

const arrayOfObjects = [
    {name: 'Fred', surname: 'Shultz'}, {name: 'Anne', surname: 'Example'}
];

const result = _.mergeWith({}, ...arrayOfObjects, (value, objValue) =>
    (value || []).concat(objValue)
);

console.log(result);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

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

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