Search code examples
javascriptarraysjavascript-objects

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:

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