I Want to split objects by assessment unit ids.
I have this
{
"name": "test",
"description": "test",
"asessment_units[]": ["2", "4", "5","8"]
}
and from this object I want four objects (because I have 4 elements in the assessment unit).
1 st object
{
"name": "test",
"description": "test",
"asessment_units[]": ["2"]
}
2nd object
{
"name": "test",
"description": "test",
"asessment_units[]": ["4"]
}
3rd object
{
"name": "test",
"description": "test",
"asessment_units[]": ["5"]
}
4th object
{
"name": "test",
"description": "test",
"asessment_units[]": ["8"]
}
CodePudding user response:
Maybe you could use Array.prototype.map
and Object.assign
:
const obj = {
name: "test",
description: "test",
"asessment_units[]": ["2", "4", "5", "8"],
};
const splitObjs = obj["asessment_units[]"].map(unit =>
Object.assign({}, obj, {
"asessment_units[]": [unit],
})
);
console.log(splitObjs);
CodePudding user response:
You can use Array.prototype.map()
on asessment_units[]
to achieve the transformation. Spread name
and description
keys of the object as they are common and insert respective value in an array inside the callback of map
.
const obj = {
"name": "test",
"description": "test",
"asessment_units[]": ["2", "4", "5","8"]
}
const res = obj['asessment_units[]'].map((val,index)=>{
return {...obj, ['asessment_units[]'] : [val]}
})