2017-09-24 82 views
1

我對java腳本很新穎。例如,如果我有一個對象,有沒有一種方法可以根據Javascript中的'Value'獲取關聯值

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

現在我知道國家&狀態值,我必須得到它的資本。

+0

您的內部數組沒有密鑰。 –

+0

您的JSON數組無效 – Thusitha

+0

瞭解如何迭代數組和對象以及如何獲取鍵值對。 – wrangler

回答

0

states性質的波普爾對象,則可以使用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; }

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; 
      } 
     }); 
    } 
}); 
+0

'map'返回一個新的數組,你可以使用'some',如果找到則返回'true',以結束迭代。 –

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); 
相關問題