简体   繁体   中英

Combine objects with the same key with lodash

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

This is the original 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" }
        ]
    }
]

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

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

Use _.groupBy() , and then use _.mergeWith() to combine each group to a single object:

 const data = [{"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"}]}]; const result = _(data) .groupBy('foo') .map((g) => _.mergeWith({}, ...g, (obj, src) => _.isArray(obj) ? obj.concat(src) : undefined)) .value(); console.log(result); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM