简体   繁体   English

如何循环并向JSON对象添加值对?

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

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: 使用jQuery SelectBox插件我正在尝试创建一个如下所示的JSON对象,其中'value''name'是选择框的值对:

'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: 目前,要仅显示'name' ,我使用以下内容:

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, ie I can't do: jsonObj.push({data[i].id:data[i].name}); 据我所知,JavaScript似乎不喜欢使用变量作为标识符,即我不能这样做: 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? 我怎样才能创建我需要的那种JSON对象,以便根据需要使Select Box工作?

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 通过这种方式,您将拥有一个对象,该对象具有“data”中包含的“id”属性以及这些属性的值作为相对名称

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM