2015-10-08 179 views
0

我有以下數據結構:陣列搜索不工作

var map_neighbours = [{ 
    "Alaska": ["UstKamchatsk", "Yukon"] 
}, { 
    "Algeria": ["Chad", "Egypt", "SierraLeone", "Spain"] 
}, { 
    "AntarticWildlifeTerritory": ["AustralianAntarticTerritory", "SouthAfricanAntarticTerritory"] 
}, .....] 

用戶通過頁面選擇一個區域,我通過這個結構要循環,找到區域,然後通過分圈區域(在相應位置)。

因此,例如,對於Algeria我想要"Chad", "Egypt", "SierraLeone", "Spain"一個循環出來。

我曾嘗試的這沒有成功幾個變化(region由用戶如上所述提供):

var neighbourArray = map_neighbours[region]; 

$.each(neighbourArray, function(idx, val) { 

    console.log("Neighbours= " + neighbourArray[region][idx]); 

}); 

$.each(map_neighbours, function(outer, val) { 

    if (map_neighbours[outer] == region) { 

     neighbourArray = (map_neighbours[outer][]); 

     $.each(neighbourArray, function(inner, val) { 

      console.log("Neighbours= " + neighbourArray[outer][inner]); 

     }); 

    ); 

}; 

感謝您的任何建議。

+0

是''=>'應該在那裏,還是應該是':'? –

回答

2

根據您目前的結構,你需要遍歷數組了,看該項目是否具有輸入值像

var map_neighbours = [{ 
 
    "Alaska": ["UstKamchatsk", "Yukon"] 
 
}, { 
 
    "Algeria": ["Chad", "Egypt", "SierraLeone", "Spain"] 
 
}, { 
 
    "AntarticWildlifeTerritory": ["AustralianAntarticTerritory", "SouthAfricanAntarticTerritory"] 
 
}]; 
 

 
var input = 'Algeria', 
 
    result; 
 
$.each(map_neighbours, function(i, item) { 
 
    if (item[input]) { 
 
    result = item[input]; 
 
    return false; 
 
    } 
 
}) 
 

 
if (result) { 
 
    snippet.log(JSON.stringify(result)); 
 
} else { 
 
    snippet.log('not found') 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> 
 
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>


但更好結構的關鍵處理情況是使用鍵值對象而不是數組對象

var map_neighbours = { 
 
    "Alaska": ["UstKamchatsk", "Yukon"], 
 
    "Algeria": ["Chad", "Egypt", "SierraLeone", "Spain"], 
 
    "AntarticWildlifeTerritory": ["AustralianAntarticTerritory", "SouthAfricanAntarticTerritory"] 
 
}; 
 

 
var input = 'Algeria', 
 
    result = map_neighbours[input]; 
 

 
if (result) { 
 
    snippet.log(JSON.stringify(result)); 
 
} else { 
 
    snippet.log('not found') 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> 
 
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

+0

真棒,你的第二個演示是非常好的建議,謝謝! – TheRealPapa