I’ve got an object:
const costCentres = {
"11738838-bf34-11e9-9c1c-063863da20d0": "Refit 2018",
"f30d72f4-a16a-11e9-9c1c-063863da20d0": "Refit 2019",
"f7fa34ed-a16a-11e9-9c1c-063863da20d0": "Refit 2020"
};
What I need is an array of object like this:
[
{
id: "11738838-bf34-11e9-9c1c-063863da20d0",
type: "Cost Centre",
name: "Refit 2018",
chosen: false
},
{
id: "f30d72f4-a16a-11e9-9c1c-063863da20d0",
type: "Cost Centre",
name: "Refit 2019",
chosen: false
},
{
id: "f7fa34ed-a16a-11e9-9c1c-063863da20d0",
type: "Cost Centre",
name: "Refit 2020",
chosen: false
}
]
This is my solution so far:
let centresToEntities = []
for (const key in costCentres) {
centresToEntities.push({
id: key,
type: 'Cost Centre',
name: costCentres[key],
chosen: false
});
}
It is working but I don’t want to use for in loop.
What would be the other way to do it?
3
Answers
Use
Object.entries()
and.map()
To convert the
costCentres
object into an array of objects with the desired structure without using afor...in
loop, you can make use of theObject.entries()
method along with theArray.prototype.map()
method. Here’s an alternative solution:The
Object.entries(costCentres)
method returns an array of key-value pairs from thecostCentres
object. Then, themap()
method is used to iterate over each key-value pair and create a new object with the desired structure.This solution eliminates the need for a
for...in
loop and achieves the desired result.A slight tweak to @Barmar’s perfect solution: