2

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"]
} 
1
  • Please add the code you've attempted to your question as a minimal reproducible example. Commented Apr 27, 2022 at 10:21

2 Answers 2

3

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);

Sign up to request clarification or add additional context in comments.

Comments

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]}
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.