构建基本的 JavaScript 对象数组

Building basic javascript object array

本文关键字:对象 数组 JavaScript 构建      更新时间:2023-09-26

我不确定是因为很晚还是什么,但今晚我似乎很难思考如何构建一个非常基本的对象数组并构建它。

我正在尝试做的是收集文本字段 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);
};

如果有人能帮我解决这个问题,我将不胜感激。提前谢谢。

在这里你去工作小提琴

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);
};

假设你想要这样的输出,

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

你可以做到,

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