Struggling to find a solution for converting this list of objects based on the group array
. The challenge lies in iterating through the group Array and applying the object to multiple places when there are several groups.
Additionally, trying to disregard any group that isn't associated with anything. Attempted using the reduce
function but encountered difficulties with iterating through the group array.
let cars =
[
{
"group":[],
"name": "All Makes",
"code": ""
},
{
"group":["Group A"],
"name": "BMW",
"code": "X821"
},
{
"group":["Group B"],
"name": "Audi",
"code": "B216"
},
{
"group":["Group B"],
"name": "Ford",
"code": "P385"
},
{
"group":["Group B", "Group C"],
"name": "Mercedes",
"code": "H801"
},
{
"group":["Group C"],
"name": "Honda",
"code": "C213"
}
]
The desired outcome is:
let cars = {
"Group A": [
{
name: "BMW",
code: "X821",
}
],
"Group B": [
{
name: "Audi",
code: "B216"
},
{
name: "Ford",
code: "P385"
},
{
name: "Mercedes",
code: "H801"
}
],
"Group C":[
{
name: "Mercedes",
code: "H801"
},
{
name:"Honda",
code: "C213"
}
]
};
Attempted using reduce method for this task but struggled with replicating grouping if an object belongs to more than one group.
let result = cars.reduce(function(x, {group, name}){
return Object.assign(x, {[group]:(x[group] || [] ).concat({group, name})})
}, {});
Any suggestions to tackle this problem would be highly valued.