Iva*_*lar 4 javascript arrays 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" }
]
}
]
Run Code Online (Sandbox Code Playgroud)
我需要组合对象,所以输出如下:
[
{
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" }
]
}
]
Run Code Online (Sandbox Code Playgroud)
如何使用 lodash 或 javascript 实现这一目标?
使用_.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);Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>Run Code Online (Sandbox Code Playgroud)
您可以使用哈希表过滤和更新数据。
该提案改变了原始数据集。
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);Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }Run Code Online (Sandbox Code Playgroud)