I am using the latest versionof d3 and need to get the minimum and maximum values of a nested property of a JSON object which looks like this:
const data =
{
"Item1":{
"Property1": "11",
"Property2": "12",
},
"Item2":{
"Property1": "21",
"Property2": "22",
}
}
To get the minimum value of Property1 I know that I cannot directly use d3.min on an object so I tried to convert it first into an array by doing the following:
const min = d3.min(d3.values(data, (d) => +d.Property1))
VScode tells me that there are no errors but on the console it tells me that "values" it's not a function. What should I do?
d3.values is equivalent of Object.values which takes only one parameter while I see you are passing two parameters , so that is why an error. I have done an example snippet for you to get the minimum, for each Item object, you can map it to get property1 value which is at index 0 ( you do this again by using d3.values). You get minimum of the property1. Note: If you dont do parseInt below, your data will give minimum based on string i.e. 100 will be lesser than 2 ( take care of that)
There can be a better answer to that by replacing 0 index with indexOf(propertyname) if you have an array of Properties. You can give a try.
UPDATE: d3.values is not supported in d3v7, so use Object.values instead
const data =
{
"Item1":{
"Property1": "151",
"Property2": "12",
},
"Item2":{
"Property1": "21",
"Property2": "22",
},
"Item3":{
"Property1": "12",
"Property2": "452",
},
"Item4":{
"Property1": "100",
"Property2": "4",
}
}
const min = d3.min(Object.values(data).map(function(d) {
return parseInt(Object.values(d)[0]);}));
console.log(min);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.4.4/d3.min.js" integrity="sha512-hnFpvCiJ8Fr1lYLqcw6wLgFUOEZ89kWCkO+cEekwcWPIPKyknKV1eZmSSG3UxXfsSuf+z/SgmiYB1zFOg3l2UQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>