How to convert array to key-values

100 Views Asked by At

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"}
]
3

There are 3 best solutions below

1
On BEST ANSWER

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

0
On

You can convert the key-value pairs to entries and map their key (id) and value to objects.

const colors = {
  "red": "Red",
  "blue": "Blue"
};

const values = Object.entries(colors).map(([id, value]) => ({ id, value }));

console.log(values);
.as-console-wrapper { top: 0; max-height: 100% !important; }

2
On

Get the object's entries, then map that to the desired output format.

const obj = {
  "red": "Red",
  "blue": "Blue"
}

const result = Object.entries(obj)
  .map(([id, value]) => ({ id, value }));

console.log(result);