引用javascript对象文字数组

时间:2008-10-07 23:36:36

标签: javascript data-structures

您将如何在此结构中引用模型(Accord,CRV,Prius等)? 这是一个糟糕的结构,能够提取制作...然后使用make来获取模型...然后使用模型来获取选项?

var cars = [
    {
        "makes"   : "Honda",
        "models"   : [
            {'Accord' : ["2dr","4dr"]} ,
            {'CRV'    : ["2dr","Hatchback"]} ,
            {'Pilot'  : ["base","superDuper"] }
        ]
    }, 
    {
        "makes"   : "Toyota",
        "models"  : [
            {'Prius'   : ["green","reallyGreen"]} ,
            {'Camry'   : ["sporty","square"]} ,
            {'Corolla' : ["cheap","superFly"] }
        ]
    }
];              

由于

5 个答案:

答案 0 :(得分:7)

结构:

var cars = [
    { name: 'Honda', models: [
                { name: 'Accord', features: ['2dr', '4dr'] },
                { name: 'CRV', features: ['2dr', 'Hatchback'] },
                { name: 'Pilot', features: ['base', 'superDuper'] }
        ]},

    { name: 'Toyota', models: [
                { name: 'Prius', features: ['green', 'superGreen'] },
                { name: 'Camry', features: ['sporty', 'square'] },
                { name: 'Corolla', features: ['cheap', 'superFly'] }
        ]}
];

我写了关于遍历和其他所有内容的here

答案 1 :(得分:6)

cars [0] .models.Accord     汽车[0] .models.CRV     汽车[0] .models.Pilot (见olliej的回答)

尽管如此,使用以下访问概念可能更容易:

cars.Honda.Accord
cars.Toyota.Prius

... ...使用

var cars = {
  Honda : {
    Accord : ["2dr", "4dr"],
    CRV    : ["2dr", "Hatchback"],
    Pilot  : ["base", "superDuper"]
  },
  Toyota : {
    Prius : ["green", "reallyGreen"],
    Camry : ["sporty", "square"],
    Corolla : ["cheap", "superFly"]
  }
};

答案 2 :(得分:3)

乔纳森是正确的,但他在模型级别错过了额外的数组级别,所以它应该是

 cars[0].models[0].Accord
 cars[0].models[1].CRV

我怀疑你会发现使用以下结构更容易:

var cars = [
{makes  : "Honda",
 models  : {
    Accord : ["2dr","4dr"],
    CRV  : ["2dr","Hatchback"],
    Pilot: ["base","superDuper"]  
 }
}, 
{makes   :"Toyota",
 models  : {
    Prius   : ["green","reallyGreen"],
    Camry   : ["sporty","square"],
    Corolla : ["cheap","superFly"]
 }
}];

其中models数组被对象(或关联数组,如果你喜欢)替换

[edit(olliej):在第二个例子中整理代码]

答案 3 :(得分:2)

您可以使用以下代码遍历模型:

for (var i = 0, carslen = cars.length; i < carslen; i++) {
    for (var j = 0, modelslen = cars[i].models.length; j < modelslen; j++) {
        // do something with cars[i].models[j]
    }
}

但我同意Olliej关于将JSON的结构更改为他的格式。

答案 4 :(得分:0)

如果我是你,我不会把你的所有数据都归结为一个大的多维数组/对象文字混乱。我将封装每个对象并使用方法来访问数据。它会使你的大脑陷入困境。