使用lodash将对象与相同的键组合在一起 [英] Combine objects with the same key with lodash

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

问题描述

我有一个对象数组。我需要组合数组中具有相同键的所有对象。

I have an array of objects. I need to combine all the objects on the array that have the same key.

这是原始数组:

[
    {
        foo: "A",
        bar: [
            { baz: "1", qux: "a" },
            { baz: "2", qux: "b" }
        ]
    },
    {
        foo: "B",
        bar: [
            { baz: "3", qux: "c" },
            { baz: "4", qux: "d" }
        ]
    },
    {
        foo: "A",
        bar: [
            { baz: "5", qux: "e" },
            { baz: "6", qux: "f" }
        ]
    },
    {
        foo: "B",
        bar: [
            { baz: "7", qux: "g" },
            { baz: "8", qux: "h" }
        ]
    }
]

我需要组合对象,以便输出如下:

I need to combine the objects so the output is as follows:

[
    {
        foo: "A",
        bar: [
            { baz: "1", qux: "a" },
            { baz: "2", qux: "b" },
            { baz: "5", qux: "e" },
            { baz: "6", qux: "f" }
        ]
    },
    {
        foo: "B",
        bar: [
            { baz: "3", qux: "c" },
            { baz: "4", qux: "d" },
            { baz: "7", qux: "g" },
            { baz: "8", qux: "h" }
        ]
    }
]

如何使用lodash或javascript实现此目的?

How can I achieve this with lodash or javascript?

推荐答案

您可以过滤并使用哈希表更新数据。

You could filter and update the data with a hash table.

此提案会改变原始数据集。

This proposal mutates the original data set.

var array = [{ foo: "A", bar: [{ baz: "1", qux: "a" }, { baz: "2", qux: "b" }] }, { foo: "B", bar: [{ baz: "3", qux: "c" }, { baz: "4", qux: "d" }] }, { foo: "A", bar: [{ baz: "5", qux: "e" }, { baz: "6", qux: "f" }] }, { foo: "B", bar: [{ baz: "7", qux: "g" }, { baz: "8", qux: "h" }] }],
    hash = Object.create(null),
    result = array.filter(function (o) {
        if (!hash[o.foo]) {
            hash[o.foo] = o.bar;
            return true;
        }
        Array.prototype.push.apply(hash[o.foo], o.bar);
    });

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }

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

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