Code Junkie
Code Junkie

Reputation: 7788

Javascript Json Obj dynamic array var name

I have a group of autocomplete text menu's I'm attempting to tie together to work similar to a year make model select menu list. You first fill in the year, then it filters the make, then filters the model. My fields filter perfectly, however I'm looking to disable and clear fields that lack a populated filter by field. for example, if the year is null, then the make model field is disabled, or if you clear the make, it will also clear the model field and set it to be disabled.

My thought was to assign the fields to a group and pass that group into a json object as an array. Example,

the JS is loaded one time and init function is called for each textfield.

spec.group = yearMakeModelGroup

spec.id = fieldId

var group={};

init = function(spec) {
    var groupId = spec.group;

    if(!group.hasOwnProperty(groupId)) {                
        group = {groupId:[]};
    }

    group.groupId.push(spec.id);
};

I can't figure out how to dynamically create an array name so that I could use this code with other groups on the page. Example yearMakeModelGroup = year, make, model plus forsaleGroup = forsale,forsalebyowner,auto.

Upvotes: 2

Views: 570

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

You need to create an object and then use the bracket notation(member operator) to create a dynamic key

if(!group.hasOwnProperty(groupId)) {     
    var obj = {};
    obj[groupId] = [];
    group = obj;
}

Upvotes: 1

Related Questions