【问题标题】:Combine objects with the same key with lodash使用 lodash 组合具有相同键的对象
【发布时间】:2017-11-30 15:13:11
【问题描述】:

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

这是原始数组:

[
    {
        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 实现这一点?

【问题讨论】:

  • 你的对象结构不对。

标签: javascript arrays lodash


【解决方案1】:

使用_.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>

【讨论】:

    【解决方案2】:

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

    这个提议改变了原始数据集。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-13
      • 1970-01-01
      • 2021-10-16
      • 1970-01-01
      • 1970-01-01
      • 2018-05-22
      • 1970-01-01
      相关资源
      最近更新 更多