如何将数组转换为键值

How to convert array to key-values

我有以下数组:

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

我想把它转换成这样的键值对:

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

您可以将键值对转换为条目并将它们的键 (id) 和 value 映射到对象。

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

获取对象的 entries, then map 到所需的输出格式。

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

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

console.log(result);

您可以使用 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);