簡體   English   中英

使用lodash將對象與相同的鍵組合在一起

[英]Combine objects with the same key with lodash

我有一個對象數組。 我需要組合陣列上具有相同鍵的所有對象。

這是原始數組:

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

我需要組合對象,所以輸出如下:

[
    {
        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實現這一目標?

您可以使用哈希表過濾和更新數據。

該提議改變了原始數據集。

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

使用_.groupBy() ,然后使用_.mergeWith()將每個組合並到一個對象:

 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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM