gpt4 book ai didi

javascript - 如何将字典添加到列表中?

转载 作者:行者123 更新时间:2023-12-01 00:35:39 32 4
gpt4 key购买 nike

我正在尝试创建一个 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/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com