Distructure and array of object and create a new array of object with a new value from the array keys in Javascript.
Existing Array of object is this –
[
{
"Semester One" : [
{
id:"1",
name:"Name1",
},
{
id:"2",
name:"Name2",
}
],
"Semester Two" : [
{
id:"3",
name:"Name3",
},
{
id:"4",
name:"Name4",
}
]
}
]
what I want to achive, is this :
[
{
id:"1",
name:"Name1",
semester:"Semester One" // array key
},
{
id:"2",
name:"Name2",
semester:"Semester One" // array key
},
{
id:"3",
name:"Name3",
semester:"Semester Two" // array key
},
{
id:"4",
name:"Name4",
semester:"Semester Two" // array key
},
]
I am able to successfully create an array of objects with a value, but I can’t access the array keys like "Semester One, Semester Two"
Here is what I have done so far –
const arrObj = [];
paperList.forEach((element) => {
for (const key in element) {
element[key].forEach((e, i) => {
arrObj.push({
...e,
semester: "", // don't know how to get this value
isChecked: "",
});
});
}
});
console.log(arrObj);
2
Answers
you can achieve the array like this, use a foreach and push to new array.
Another solution you can use (shorter) :