-2

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"}
]
bigmammoo
  • 101
  • 1
  • 1
  • 11

3 Answers3

1

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; }
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
1

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);
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
1

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);
DecPK
  • 24,537
  • 6
  • 26
  • 42