Noobster Noobster -4 years ago 98
Javascript Question

Output array without numeric index

The following code:

for(i=0; i<3; i++){
a = {};
a['name' + i] = i;
data.push(a);
}


...outputs the following array:

{
1:{name0:0},
2:{name1:1},
3:{name2:2}
}


How can I amend the code so that it outputs the array as follows:

{
name0:0,
name1:1,
name2:2
}


The reason I need to do this, is that I'd like to be able to reference my array later on like so:
data[name1]
, instead of having to loop through the entire array to look for the value that I need.

Answer Source

well you should use data directly as an object, rather than having it as an array (and thus having it as an array of objects)

 for(i=0; i<3; i++){
    data['name' + i] = i;
}

Keep in mind that data should be an object (initialized as var data = {})

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download