How to loop through & add pairs of values to JSON object?

戏子无情 提交于 2019-12-21 02:54:13

问题


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



来源:https://stackoverflow.com/questions/7255058/how-to-loop-through-add-pairs-of-values-to-json-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!