How to loop through & add pairs of values to JSON

2019-03-22 07:52发布

问题:

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?

回答1:

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