简体   繁体   中英

Is there a way to get associated values based on 'Value' in Javascript

I am pretty new to java script. for example if I have an object,

var countryData = [{name :"India",[{state : "AP",capital:"vjw"}, {state:"TS",capital:"hyd"}] } {name :"Belgium",[{state : "AL",capital:"Montgomery"}, {state:"AK",capital:"Juneau"}] }]

Now I know the country & state value and I have to get its capital.

First lets fix the data array

var countryData = [
    { name: "India", 'states': [
            { state: "AP", capital: "vjw" },
            { state: "TS", capital: "hyd" }
        ]
    },
    { name: "Belgium", 'states': [
            { state: "AL", capital: "Montgomery" },
            { state: "AK", capital: "Juneau" }
        ]
    }
];

Then you can iterate over this using array maps and simple conditions

 let stateCapital = '';

 countryData.map((country) => {
    if (country.name === 'India') {
        country.states.map((state) => {
            if (state.state === 'AP') {
                stateCapital = state.capital;
            }
        });
    }
});

With a poper object with states properties, you could use Array#find .

 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); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

The object in your countryData is incorrect; see and test this code:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM