作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试创建一个 for 循环,将值存储在字典中,并且每次迭代都会将此字典附加到列表中。
已经尝试使用push()和索引列表附加,但没有成功。
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);
结果并不如我所愿:
// Actual result
[
{ label: 'atrib3', values: [ 1000, 2000, 3000, 4000 ] },
{ label: 'atrib3', values: [ 1000, 2000, 3000, 4000 ] },
{ label: 'atrib3', values: [ 1000, 2000, 3000, 4000 ] }
]
我需要这个:
// Expected result
[
{ label: 'atrib1', values: [ 10, 20, 30, 40 ] },
{ label: 'atrib2', values: [ 100, 200, 300, 400 ] },
{ label: 'atrib3', values: [ 1000, 2000, 3000, 4000 ] }
]
我做错了什么?
最佳答案
您的代码的问题在于您“填充”dictionario
的位置 - 所有输出都使用和修改这个对象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;
}
一种解决方案是更改代码,以便每次迭代都有一个新的 dictionario
对象可供使用
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;
}
但是,对于整洁的 ES6+ 解决方案:
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));
关于javascript - 如何将字典添加到列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58152666/
我是一名优秀的程序员,十分优秀!