I encountered a situation where I had an array of objects with duplicate ids. Each object linked to the id contains two properties: A and B. In the first index of the array, property A has a value while property B is null. Conversely, in the second index, property A is null and property B has a value. The goal is to merge these two indexes based on the same id. However, the output currently does not display values for both properties A and B - one of them remains null.
Array
{
id: 123,
A: “value A1”,
B: null
},
{
id: 123,
A: null,
B: “value b”
},
{
id: 123,
A: “value A2”,
B: null
},
{
id: 456,
A: "a2 value",
B: "b2 value"
}
Code
var output = _.groupBy(arr, function(o){
return o.id;
})
Output
{
id: 123,
A: [“value A1”, “value A2”],
B: null
},
{
id: 456,
A: ["a2 value"],
B: "b2 value"
}
Expected
{
id: 123,
A: [“value A1”, “value A2”],
B: “value b”
},
{
id: 456,
A: ["a2 value"],
B: "b2 value"
}