3

Using the jQuery SelectBox plugin I'm trying to create a JSON object which looks as follows, where 'value' and 'name' are pairs of values for a select box:

'Opt Group 1': {
    'value': 'name',
    'value': 'name',
    'value': 'name',
    'value': 'name',
    'value': 'name'
},

So that when I loop through my data, I push more data to the end of the array. Currently, to display the 'name' only, I use the following:

var jsonObj = [];
for(var i=0; i<data.length; i++){
    jsonObj.push(data[i].name);
}
console.log(jsonObj);

So far as I understand it, JavaScript doesn't seem to like using variables as identifiers, i.e. I can't do: jsonObj.push({data[i].id:data[i].name});

How might I go about creating the kind of JSON object I need, in order to get the Select Box working as needed?

Joe W
  • 998
  • 6
  • 16
  • 36

1 Answers1

17

You are making a lot of confusion between arrays and objects i think. You could do:

var jsonObj = {};
for(var i=0; i<data.length; i++){
    jsonObj[data[i].id] = data[i].name;
}

in this way you would have an object that has as properties the "id" contained in "data" and as values of those properties the relative names

Nicola Peluchetti
  • 76,206
  • 31
  • 145
  • 192
  • Well, you're not wrong that I have a lot of confusion between arrays and objects. Thanks, I'll give this a try. – Joe W Aug 31 '11 at 10:22
  • Sir, you are a gent. That works perfectly. So to confirm, this is just a JSON object? The word array doesn't really count here? – Joe W Aug 31 '11 at 10:28
  • 1
    Actually it's not a JSON object, it is a standard javascript Object. There a lot of good articles on Objects and Arrays in Javascript and it's normal to be confused! :) – Nicola Peluchetti Aug 31 '11 at 10:36