Combine objects with the same key with lodash

断了今生、忘了曾经 提交于 2019-12-04 19:14:43

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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!