Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.9k views
in Technique[技术] by (71.8m points)

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

I am trying to convert a JSON format output by a web app to a format that can be read by cytoscape.js, a graph visualization tool. I am fairly certain there is a simple javascript solution, but I am quite new to JS.

The JSON output I have is in this example format:

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

The output JSON format needed for cytoscape.js is slightly different with each element preceded by 'data :' (I assume this is acting as a key for cytoscape.js to read?)

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

I have tried parsing and then iterating through each element to concatenate the "data" piece on the front as in this snippet:

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

This seems to be a type mismatch as it returns this output three times:

data: {[object Object]}

I have seen other examples that seem to suggest that a map or reduce may be appropriate, but I do not fully understand them to implement correctly.

Any help would be greatly appreciated. Thank you!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

if you want to change your original array:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...