2013-09-22 67 views
0

我不確定是因爲它遲到還是什麼,但我似乎今晚有一個非常困難的時間,想通過構建一個非常基本的對象數組來構建它。構建基本的javascript對象數組

我想要做的是收集文本字段ID的列表,並將它們放入組變量;

groupA:{year, make, model} 
groupB:{color,body} 

我不知道如何構建我的主要組對象。我不確定它是否應該使用數組。下面是我第一次嘗試

group = {groupA:{"year","make","model","trim"},groupB:{"body","color","transmission"}} 

我試圖建立我的組對象,像這樣,但是我真的覺得我做這一切是錯誤的。

//Class variable 
    Var group = {} 

    //this method is called for every textfield 
    selectGroup = function(spec) { 
    //Group id is the group the field is assigned to, example groupA, or groupB 
    var groupId = spec.groupId; 

    //I'm checking to see if groupId exist in group object, otherwise I add it. 
    if (!group.hasOwnProperty(groupId)) { 
     var obj = {}; 
     obj[groupId] = []; 
     group = obj; 
    } 
    //spec.id is the field id, example make, model 
    group[groupId].push(spec.id); 
}; 

如果有人能幫助我解決這一切,我將不勝感激。提前致謝。

+2

缺少一個冒號和使用錯誤的數組字符:' group = {groupA:[「year」,「make」,「model」,「trim」],groupB:[「body」,「color」,「transmission」]} – mplungjan

+0

對不起,我只是寫得很快,我想我問的是如果組應該是一個groupA,groupB等數組,或者如果組應該是一個嵌套對象的對象 –

+0

如果你有需要'{「year」:1998 ,「模型」:「模型A」,「修剪」:「銀」}'你需要小寫字母「v」在「var」中 – mplungjan

回答

2

在這裏你去working fiddle

var group = {}; 

//this method is called for every textfield 
selectGroup = function (spec) { 
    //Group id is the group the field is assigned to, example groupA, or groupB 
    var groupId = spec.groupId; 

    //I'm checking to see if groupId exist in group object, otherwise I add it. 
    if (!group.hasOwnProperty(groupId)) { 
     group[groupId] = []; 
    } 
    //spec.id is the field id, example make, model 
    group[groupId].push(spec.id); 
}; 
+0

非常感謝您花時間把這個例子放在一起。 –

1

假設你想這樣的輸出,

group = {groupA:["year","make","model","trim"] , groupB:["body","color","transmission"]}, 

你可以做,

var group = {}; 

if (!group.hasOwnProperty(groupId)) {    
    group[groupId] = [];    
}   
group[groupId].push(spec.id);