我是java脚本的新手。例如,如果我有一个对象,
var countryData = [{name :"India",[{state : "AP",capital:"vjw"}, {state:"TS",capital:"hyd"}] } {name :"Belgium",[{state : "AL",capital:"Montgomery"}, {state:"AK",capital:"Juneau"}] }]
现在我知道这个国家&国家价值,我必须得到它的资本。
答案 0 :(得分:0)
首先让我们修复数据数组
var countryData = [
{ name: "India", 'states': [
{ state: "AP", capital: "vjw" },
{ state: "TS", capital: "hyd" }
]
},
{ name: "Belgium", 'states': [
{ state: "AL", capital: "Montgomery" },
{ state: "AK", capital: "Juneau" }
]
}
];
然后你可以使用数组映射和简单条件迭代它
let stateCapital = '';
countryData.map((country) => {
if (country.name === 'India') {
country.states.map((state) => {
if (state.state === 'AP') {
stateCapital = state.capital;
}
});
}
});
答案 1 :(得分:0)
使用具有list2
属性的poper对象,您可以使用Array#find
。
states
function getCapital(country, state) {
return (countryData.find(c => c.name === country) || { states: [] })
.states.find(s => s.state === state);
}
var countryData = [{ name: "India", states: [{ state: "AP", capital: "vjw" }, { state: "TS", capital: "hyd" }] }, { name: "Belgium", states: [{ state: "AL", capital: "Montgomery" }, { state: "AK", capital: "Juneau" }] }];
console.log(getCapital('Belgium', 'AL'));
console.log(countryData);
答案 2 :(得分:0)
countryData
中的对象不正确;查看并测试此代码:
var countryData = [{name :"India","0":[{state : "AP",capital:"vjw"}, {state:"TS",capital:"hyd"}] }, {name :"Belgium","0":[{state : "AL",capital:"Montgomery"}, {state:"AK",capital:"Juneau"}] }];
var country ='India';
var state ='TS';
var capital ='';
for(var i=0; i<countryData.length; i++){
if(countryData[i].name ==country){
for(var i2=0; i2<countryData[i][0].length; i2++){
if(countryData[i][0][i2].state ==state){
capital = countryData[i][0][i2].capital;
break;
}
}
}
}
alert(capital);