I have seen questions about dealing with “nested json” in d3.js and have seen that the proposed solutions are mostly to “flatten” the data (meaning creating a new variable and pushing in the data in desired level) Here two examples:
My question is : can one use one of the various array functions to access the level of the data without creating a new variable ? Handling arrays
I have an array which looks like that:
var dataset =
{"directed": false,
"graph": [],
"nodes":
[
{"Region": "X15", "Group": "EU", "id": "BE"},
{"id": "FR"},
{"id": "BG"},
{"id": "DK"},
{"id": "HR"},
{"id": "DE"}
],
"links":
[
{"source": 0, "target": 0, "weight": 0},
{"source": 0, "target": 1, "weight": 130},
{"source": 0, "target": 2, "weight": 1},
{"source": 0, "target": 3, "weight": 36},
{"source": 0, "target": 4, "weight": 4},
{"source": 0, "target": 5, "weight": 117}
],
"multigraph": false}
I have tried the following
and Iwould like to access the weight (calculating its maximum with d3.max)
dataset.links // gives me link
dataset.links[0].weight // gives me the weight of first but can't get the index to work
when using the array functions I can't get elements lower than that
d3.entries(dataset)
d3.values(dataset.links)
what am I missing ?
I hope the question makes sense.
PS: if one has to flatten the array, is there any advantage of doing it in javascript or is it the same if I create the array (eg in python) and pass it to javascript
After reading over your post again, I think I know what your trying to do.
If you want to access the weights column with something like d3.max
, you can use an accessor function.
An accessor function specifies how you want to look through an item in the array. In your case, you want a function that looks at the weight
field in each link in dataset.links
. With the link as an input, this function is quite simple:
function getWeight(link){return link.weight}
We can then use this function as the accessor function to get the max of the weight
fields in dataset.links
, as follows:
var maxWeight = d3.max(dataset.links, getWeight)
This uses the general form of the d3.max
command, d3.max(array [,accessorFcn])
.
I've set up a fiddle that does this and then alerts the max weight.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.