我有两个for循环,它们应该反汇编一个对象并以特殊方式写入一个新对象。但由于某种原因,我的对象数据被覆盖,最终结果只是最后一个条目。这是我的代码:
let j = 0, k = 0, tempCities = [];
for (let stateKey in this.countries[countryKey].states) {
if (this.countries[countryKey].states.hasOwnProperty(stateKey)) {
this.states[j] = this.states[stateKey].name;
for (let cityKey in this.states[stateKey].cities) {
if (this.states[stateKey].cities.hasOwnProperty(cityKey)) {
tempCities[k] = this.cities[cityKey].name;
}
k++;
}
k = 0;
this.cities[this.states[j]] = tempCities;
}
j++;
}
问题是这个在外循环this.cities[this.states[j]] = tempCities
我需要让对象键为this.states[j]
,并且我需要拥有所有这些,而不需要覆盖。
如何解决此问题的任何建议都将受到高度赞赏!
此外,以下是我尝试使用的示例数据(来自Firebase)
{
"cities": {
"-KuzIBwGCbJhAswAcOTk": {
"cityCounter": 1,
"name": "Sceaux-du-Gâtinais",
"state": "-KuzIBslq88OXpE_L0iy"
},
"-Kv1e75Dd2pjnropd63W": {
"cityCounter": 1,
"name": "Labelle",
"state": "-Kv1e724mJTS-6E_DZh1"
},
},
"countries": {
"-KuzIBoxiP2oksxhxFX6": {
"countryCounter": 1,
"name": "France",
"states": {
"-KuzIBslq88OXpE_L0iy": true
}
},
"-Kv1e6wxA9RwYyEYO27e": {
"countryCounter": 2,
"name": "United States",
"states": {
"-Kv1e724mJTS-6E_DZh1": true
}
}
},
"states": {
"-KuzIBslq88OXpE_L0iy": {
"cities": {
"-KuzIBwGCbJhAswAcOTk": true
},
"country": "-KuzIBoxiP2oksxhxFX6",
"name": "Centre Region",
"stateCounter": 1
},
"-Kv1e724mJTS-6E_DZh1": {
"cities": {
"-Kv1e75Dd2pjnropd63W": true,
"-Kv1eEb3D4pqd7l14KCg": true
},
"country": "-Kv1e6wxA9RwYyEYO27e",
"name": "FL",
"stateCounter": 2
}
}
}
答案 0 :(得分:0)
您需要压缩数据,如下所示:
{
"coutries": {
"-JiGh_31GA20JabpZBfa": {
"name": "United States",
"states": {
"-JiGh_31GA20JabpZBfb": true
}
}
},
"states": {
"-JiGh_31GA20JabpZBfb": {
"name": "Florida",
"country": "-JiGh_31GA20JabpZBfa",
"cities": {
"-JiGh_31GA20JabpZBfc": true
}
}
},
"cities": {
"-JiGh_31GA20JabpZBfc": {
"name": "Miami",
"state": "-JiGh_31GA20JabpZBfb",
"visited_by": {
"P1yjH4GgcFQcJUHULmTgMLC68w64": true
}
}
},
"users": {
"P1yjH4GgcFQcJUHULmTgMLC68w64": {
"cities_visited": {
"-JiGh_31GA20JabpZBfc": true
}
}
}
}