I have an array of objects. I need to combine all the objects on the array that have the same key.
This is the original 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" }
]
}
]
I need to combine the objects so the output is as follows:
[
{
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" }
]
}
]
How can I achieve this with lodash or javascript?
The _. merge() method is used to merge two or more objects starting with the left-most to the right-most to create a parent mapping object. When two keys are the same, the generated object will have value for the rightmost key.
If both arrays are in the correct order; where each item corresponds to its associated member identifier then you can simply use. var merge = _. merge(arr1, arr2);
The first detail is that merge() copies objects recursively, so _. merge() is a deep copy whereas _. assign() is a shallow copy.
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>
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With