Reputation: 3
I am trying to make a for loop that stores values in a dictionary and each iteration appends this dictionary to a list.
Already tried to attach using push() and index list, but no sucess.
json = {
"MUNICIPIOS":[
{"ATRIBUTOS":["atrib1","atrib2","atrib3"],"VALORES": [10, 100, 1000]},
{"ATRIBUTOS":["atrib1","atrib2","atrib3"],"VALORES": [20, 200, 2000]},
{"ATRIBUTOS":["atrib1","atrib2","atrib3"],"VALORES": [30, 300, 3000]},
{"ATRIBUTOS":["atrib1","atrib2","atrib3"],"VALORES": [40, 400, 4000]}
]
};
var atributos = json["MUNICIPIOS"][0]["ATRIBUTOS"];
var municipios = json["MUNICIPIOS"];
var dimensoes = [];
var dicionario = {label:"", values:[]};
for (var atr = 0; atr < atributos.length; atr++){
dicionario.label = atributos[atr];
valores = [];
for (var mun=0; mun < municipios.length; mun++){
valores.push(municipios[mun]["VALORES"][atr]);
dicionario.values = valores;
}
//dimensoes.push(dicionario);
dimensoes[atr] = dicionario;
}
console.log(dimensoes);
The result is not as I wish:
// Actual result
[
{ label: 'atrib3', values: [ 1000, 2000, 3000, 4000 ] },
{ label: 'atrib3', values: [ 1000, 2000, 3000, 4000 ] },
{ label: 'atrib3', values: [ 1000, 2000, 3000, 4000 ] }
]
I need this:
// Expected result
[
{ label: 'atrib1', values: [ 10, 20, 30, 40 ] },
{ label: 'atrib2', values: [ 100, 200, 300, 400 ] },
{ label: 'atrib3', values: [ 1000, 2000, 3000, 4000 ] }
]
What am I doing wrong?
Upvotes: 0
Views: 48
Reputation: 1
The issue with your code is where you "populate" dicionario
- this one object is used and modified for all outputs dimensoes[atr]
var dicionario = {label:"", values:[]};
for (var atr = 0; atr < atributos.length; atr++){
dicionario.label = atributos[atr];
// snip - rest of your code
dimensoes[atr] = dicionario;
}
One solution is to change the code so that each iteration has a new dicionario
object to work with
var dicionario = {label:"", values:[]};
for (var atr = 0; atr < atributos.length; atr++){
dicionario = {label:atributos[atr], values:[]};
//dicionario.label = atributos[atr]; not required as it is set above
// snip - rest of your code
dimensoes[atr] = dicionario;
}
However, for a neat and tidy ES6+ solution:
const json = {
"MUNICIPIOS":[
{"ATRIBUTOS":["atrib1","atrib2","atrib3"],"VALORES": [10, 100, 1000]},
{"ATRIBUTOS":["atrib1","atrib2","atrib3"],"VALORES": [20, 200, 2000]},
{"ATRIBUTOS":["atrib1","atrib2","atrib3"],"VALORES": [30, 300, 3000]},
{"ATRIBUTOS":["atrib1","atrib2","atrib3"],"VALORES": [40, 400, 4000]}
]
};
const atributos = json.MUNICIPIOS[0].ATRIBUTOS;
const municipios = json.MUNICIPIOS;
const dimensoes = atributos.map((label, atr) => ({
label,
values: municipios.map(municipio => municipio.VALORES[atr])
}));
console.log(JSON.stringify(dimensoes, null, 4));
Upvotes: 2