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

Viewed 43

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!

2 Answers

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

you can do this

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

Related