构建基本的javascript对象数组

时间:2013-09-22 04:46:41

标签: javascript jquery

我不确定是不是因为它已经晚了或什么,但我今晚似乎很难通过构建一个非常基本的对象阵列并构建它来思考。

我要做的是收集一个文本字段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 个答案:

答案 0 :(得分: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);
};

答案 1 :(得分:1)

假设您想要这样的输出,

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

你可以,

var group = {};

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