'How to clone object with different specific values
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"]
}
Solution 1:[1]
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);
Solution 2:[2]
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]}
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Pranay Binju |
