Search code examples
javascriptarrayskeykey-valuekey-pair

How to convert array to key-values


I have the following array:

{
  "red": "Red",
  "blue": "Blue"
}

And I want to convert it to a key-value pair like this:

[
{"id":"red", "value":"Red"},
{"id":"blue","value":"Blue"}
]

Solution

  • You can achieve this using Object.entries and map

    const obj = {
      red: "Red",
      blue: "Blue",
    };
    
    const result = Object.entries(obj).map((o) => {
      const [prop, val] = o;
      return {
        id: prop,
        value: val
      };
    });
    
    console.log(result);