I have JSON array with one object consisting of nodes and links.
data = [Object]=[ { nodes: Array[..] ,links: Array[…] } ]
This is all fine, but for accessing the links for example I have to use data[0].links, which is a bit annoying. I would like the array to be an object, so that data.links gives access to the links. I have tried to set:
data = data[0];
But then the array of Objects, data.links, are displayed as “undefined”.It seems like when a specific element is accessed the value is displayed, for example data.links[3].name. Why is that?
Edit:
More specifically:
if data = [ { nodes: Array[… ] ,links: Array[…] } ] =>
console.log(data[0].links); //shows the data[0].links[0].name = value in the console
if data = { nodes: Array[… ] ,links: Array[…] } =>
console.log(data.links); //shows data[0].links[0].name = undefined
but interestingly
console.log(data.links[0].name); //shows the correct value.
A couple of solutions:
If you control the JSON output, simply remove the enclosing brackets
[]those are basically wrapping your object in an array.If you don’t control the JSON just simply assign the zero index of the array to the variable you actually want to work with.
Unfortunately, ‘links’ is an array. To access a member of that array, you will need to access its index value.