How to loop through & add pairs of values to JSON

2019-03-22 07:30发布

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条回答
地球回转人心会变
2楼-- · 2019-03-22 07:59

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

查看更多
登录 后发表回答