我可以创建以下内容并使用它引用

area[0].states[0] 
area[0].cities[0]

var area = [
        {
         "State"   : "Texas",
         "Cities"  : ['Austin','Dallas','San Antonio']
        },
        {
         "State"   :"Arkansas",
         "Cities"  : ['Little Rock','Texarkana','Hot Springs']
        }
       ] ;

我如何重组“区域”,以便如果我知道州的名称,我可以在引用中使用它来获取城市数组?

谢谢

编辑 尝试用我收到的答案来实现(感谢 @Eli Courtwright、@17 of 26 和 @JasonBunting),我意识到我的问题不完整。我需要第一次通过索引循环遍历“区域”,然后当我选择“状态”时,我需要使用“状态”的值循环返回一个结构以获得关联的“城市”。我确实想从上面的结构开始(尽管我可以自由地按照我想要的方式构建它),并且我不介意类似于@eli的答案的转换(尽管我无法使该转换起作用)。第一个问题应该更完整。尝试实现 2 个选择框,其中第一个选择框填充第二个选择框...我将在页面加载时在 js 文件中加载此数组结构。

有帮助吗?

解决方案

如果你想一开始就以这种方式创建它,只需说

area = {
    "Texas": ['Austin','Dallas','San Antonio']
}

等等。如果您问如何获取现有对象并将其转换为此对象,只需说

states = {}
for(var j=0; j<area.length; j++)
    states[ area[0].State ] = area[0].Cities

运行上面的代码后,你可以说

states["Texas"]

这会返回

['Austin','Dallas','San Antonio']

其他提示

var area = 
{
    "Texas" : { "Cities"  : ['Austin','Dallas','San Antonio'] },
    "Arkansas" : { "Cities"  : ['Little Rock','Texarkana','Hot Springs'] }
};

然后你可以这样做:

area["Texas"].Cities[0];

(在答案的帮助下,我让它按照我想要的方式工作。我在下面的代码中修复了所选答案中的语法)

带有以下选择框

<select id="states" size="2"></select>
<select id="cities" size="3"></select>

以及此格式的数据(在 .js 文件中或以 JSON 形式接收)

var area = [
    {
     "states"   : "Texas",
     "cities"  : ['Austin','Dallas','San Antonio']
    },
    {
     "states"   :"Arkansas",
     "cities"  : ['Little Rock','Texarkana','Hot Springs']
    }
   ] ;

这些 JQuery 函数将根据州选择框的选择填充城市选择框

$(function() {      // create an array to be referenced by state name
 state = [] ;
 for(var i=0; i<area.length; i++) {
  state[area[i].states] = area[i].cities ;
 }
});

$(function() {
 // populate states select box
 var options = '' ;
 for (var i = 0; i < area.length; i++) {
  options += '<option value="' + area[i].states + '">' + area[i].states + '</option>'; 
 }
 $("#states").html(options);   // populate select box with array

 // selecting state (change) will populate cities select box
 $("#states").bind("change",
   function() {
    $("#cities").children().remove() ;      // clear select box
    var options = '' ;
    for (var i = 0; i < state[this.value].length; i++) { 
     options += '<option value="' + state[this.value][i] + '">' + state[this.value][i] + '</option>'; 
    }
    $("#cities").html(options);   // populate select box with array
   }        // bind function end
 );         // bind end 
});

这将为您提供基于知道州名的城市数组:

var area = {
   "Texas" : ["Austin","Dallas","San Antonio"], 
   "Arkansas" : ["Little Rock","Texarkana","Hot Springs"]
};

// area["Texas"] would return ["Austin","Dallas","San Antonio"]
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top