我有一个对象数组。我需要组合阵列上具有相同键的所有对象。
这是原始数组:
PS C:\> $Obj1 = [PSCustomObject]@{
Property1 = 'Value1'
Property2 = 'Value2'
Property3 = 'Value3'
Property4 = 'Value4'
Property5 = 'Value5'
}
PS C:\> $Obj2 = [PSCustomObject]@{
Property1 = 'Value1'
Property2 = 'Value2'
Property3 = 'Value3'
Property4 = 'Value4'
Property5 = 'Value5'
}
PS C:\> Test-Objects $Obj1 $Obj2
True
PS C:\> $Obj2 | Add-Member -MemberType 'NoteProperty' -Name 'Prop6' -Value 'Value6'
PS C:\> Test-Objects $Obj1 $Obj2
False
我需要组合对象,以便输出如下:
[
{
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" }
]
}
]
如何使用lodash或javascript实现此目的?
答案 0 :(得分:3)
您可以使用哈希表过滤和更新数据。
此提案改变了原始数据集。
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; }
答案 1 :(得分: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>
&#13;