首页 > 解决方案 > 将对象格式化为所有对象数组

问题描述

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

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

转变为。

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

标签: javascriptalgorithmdata-structures

解决方案


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


推荐阅读