I want the regionValue to return as the key of the Region object, but it instead returns null?
My goal is to get:
{
value: 1122000,
Tid: '2020',
ContentsCode: 'Samlet inntekt, median (kr)',
HusholdType: 'Par med barn 0-17 år',
Region: 'Ringerike',
regionValue:"3007"
},
but this is what i've tried so far:
const JSONstat = require("jsonstat-toolkit");
var url="https://data.ssb.no/api/v0/dataset/49678.json?lang=no";
function test(){
return JSONstat(url).then(main);
}
async function main(j){
var ds=j.Dataset(0);
let y="Region"
let array = ds.toTable( { type : "arrobj" } ,function( d ){
if ( d.value!==null){
d.regionValue = ds.Dimension(y).Category(d.Region).id
return d;
}
})
console.log(array)
}
test()
It appears that the Region dimension is only available as an object with ID -> Label so you can not directly search by Region name to obtain the ID.
As a workaround, you can create a new inverted object with Label => ID and use that to retrieve the RegionValue from the Region.
So in code
assoc = {}
main method, loop all the Regions and populate your inverted objectPlease note that the labels were displaying a date, so I used split to remove useless information that wouldn't allow a direct match on the Region name.
for(const key in ds.__tree__.dimension.Region.category.label) {
let label = ds.__tree__.dimension.Region.category.label[key].split('(')[0].trim()
assoc[label] = key
}
assoc object you've just populated and assign its value to d.regionValueif (d.value !== null) {
d.regionValue = assoc[d.Region]
return d;
}
When you output your array, it will show like this
0:
ContentsCode: "Samlet inntekt, median (kr)"
HusholdType: "Alle husholdninger"
Region: "Halden"
Tid: "2020"
regionValue: "0101"
value: 616000
Here's the full script
var url = "https://data.ssb.no/api/v0/dataset/49678.json?lang=no";
assoc = {}
function test() {
return JSONstat(url).then(main);
}
async function main(j) {
var ds = j.Dataset(0);
for(const key in ds.__tree__.dimension.Region.category.label) {
let label = ds.__tree__.dimension.Region.category.label[key].split('(')[0].trim()
assoc[label] = key
}
let array = ds.toTable({
type: "arrobj"
}, function (d) {
if (d.value !== null) {
d.regionValue = assoc[d.Region]
return d;
}
})
console.log(array)
}
test()