将数组对象合并在一起 - lodash [英] merge array object together - lodash

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

问题描述

所以我有一系列这样的项目:

So I have an array of items like this:

items = [
    {
        amount: 2,
        name: 'bike'
    },
    {
        amount: 1,
        name: 'boat'
    },
    {
        amount: 3,
        name: 'bike'
    }
]

现在,我想合并这个数组,这样就不会有重复的自行车,但仍然知道总共有多少辆自行车。

Now, I would like to merge this array so that there would be no duplicates of bike and still know how many bikes there are in total.

所以我的结果数组看起来像这样:

so my result array would look like this:

items = [
    {
        amount: 5,
        name: 'bike'
    },
    {
        amount: 1,
        name: 'boat'
    }
]

为了保持我的代码简短,我建议使用 lodash 我一直在研究将数组合并在一起的不同方法。但说实话,弄清楚最好的方法是多么令人困惑,这就是我要问你们的原因^^

In order to keep my code short I have been advised using lodash and I've been looking at the different ways to merge arrays together. But to be honest it quite confusing to figure out what the best approach would be, which is why I'm asking you guys ^^

推荐答案

您可以使用 .groupBy 与< a href =https://lodash.com/docs#map =nofollow> .map _。总和 ,用于计算金额,像这样

You can use .groupBy with .map, and _.sum for calculate amount, like so

var items = [{
    amount: 2,
    name: 'bike'
}, {
    amount: 1,
    name: 'boat'
}, {
    amount: 3,
    name: 'bike'
}];

var res = _(items)
    .groupBy('name')
    .map(function (el, name) {
        return {
            name: name,
            amount: _.sum(el, 'amount')
        };
    })    
    .value();

console.log(res);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.7.0/lodash.min.js"></script>
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

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

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