具有文字和数组混合的Javascript数组 [英] Javascript array with a mix of literals and arrays

查看:55
本文介绍了具有文字和数组混合的Javascript数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用

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']
        }
       ] ;

我如何重组区域,这样如果我知道州的名称,我可以使用它参考了一系列城市?

How could I restructure "area" so that if I know the name of the state, I can use it in a reference to get the array of cities?

谢谢

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

EDIT Attempting to implement with the answers I received (thanks @Eli Courtwright, @17 of 26, and @JasonBunting) I realize my question was incomplete. I need to loop through "area" the first time referencing "state" by index, then when I have the selection of the "state", I need to loop back through a structure using the value of "state" to get the associated "cities". I do want to start with the above structure (although I am free to build it how I want) and I don't mind a conversion similar to @eli's answer (although I was not able to get that conversion to work). Should have been more complete in first question. Trying to implement 2 select boxes where the selection from the first populates the second...I will load this array structure in a js file when the page loads.

推荐答案

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

If you want to just create it that way to begin with, just say

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

等等。如果您正在询问如何获取现有对象并将其转换为此对象,请说

and so on. If you're asking how to take an existing object and convert it into this, just say

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

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

After running the above code, you could say

states["Texas"]

将返回

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

这篇关于具有文字和数组混合的Javascript数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆