将对象格式化为所有对象数组

这个问题很简单,没有明确的答案。我有一个对象,我的目标是将每个值和键转换为对象并推送到数组,例如下面的示例以使其清楚。

{
  title: "This is a Title",
  name: "This is a name"
}

转变为。

[
  {title: "This is a Title"},
  {name: "This is a name"}
]

回答

使用Object.entries对象转换为数组,然后映射数组到你想要的格式对象数组:

const obj = {
title: "This is a Title",
name: "This is a name"
};
const arr = Object.entries(obj)
.map(([key, value]) => ({ [key]: value }));
console.log(arr);

以上是将对象格式化为所有对象数组的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>