2013-09-22 167 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);