Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create array of objects from keys and values of another object

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

Use Object.entries() and .map()

const costCentres = {
  "11738838-bf34-11e9-9c1c-063863da20d0": "Refit 2018",
  "f30d72f4-a16a-11e9-9c1c-063863da20d0": "Refit 2019",
  "f7fa34ed-a16a-11e9-9c1c-063863da20d0": "Refit 2020"
};

let centresToEntities = Object.entries(costCentres).map(([key, value]) => ({
  id: key,
  type: 'Cost Centre',
  name: value,
  chosen: false
}));

console.log(centresToEntities);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading