尝试更改 JSON 的格式以使用新键嵌套元素

Trying to change format of JSON to nest elements with new key

我正在尝试将 Web 应用程序输出的 JSON 格式转换为可由 cytoscape.js(一种图形可视化工具)读取的格式。我相当确定有一个简单的 javascript 解决方案,但我对 JS 很陌生。

我的 JSON 输出是这个示例格式:

[
{"name": "squirtle", "type": "water"}, 
{"name": "charmander", "type": "fire"}, 
{"name": "bulbasaur", "type": "grass"}
]

cytoscape.js 所需的输出 JSON 格式与前面带有 'data :' 的每个元素略有不同(我假设这是 cytoscape.js 读取的关键?)

[
{ "data": {"name": "squirtle", "type": "water"} },
{ "data": {"name": "charmander", "type": "fire"} },
{ "data": {"name": "bulbasaur", "type": "grass"} }
]

我已经尝试解析然后遍历每个元素以连接前面的“数据”片段,如以下代码片段所示:

  pokemonJSON.forEach(element => {
    element = 'data: {' + element +'}';  
    console.log(element)
  });

这似乎是类型不匹配,因为它 returns 输出了三次:

data: {[object Object]}

我看到其他示例似乎表明 map 或 reduce 可能是合适的,但我不完全理解它们是否正确实施。

如有任何帮助,我们将不胜感激。谢谢!

你可以做到这一点

const data = [{
    "name": "squirtle",
    "type": "water"
  },
  {
    "name": "charmander",
    "type": "fire"
  },
  {
    "name": "bulbasaur",
    "type": "grass"
  }
];

const output = data.map(x => {
  return {
    data: x
  }
});

console.log(output);

如果您想更改原始数组:

const pokemonJSON = 
  [ { "name": "squirtle",   "type": "water" }
  , { "name": "charmander", "type": "fire"  }
  , { "name": "bulbasaur",  "type": "grass" }
  ]

pokemonJSON.forEach((el,i,arr)=>
  {
  arr[i] = { data : el }
  })
  
console.log( pokemonJSON )
.as-console-wrapper { max-height: 100% !important; top: 0; }