Javascript 如何循环并将成对的值添加到 JSON 对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7255058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:29:57  来源:igfitidea点击:

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

javascriptjqueryarraysjsonjquery-selectbox

提问by Joe W

Using the jQuery SelectBox pluginI'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, i.e. 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 根据需要工作?

回答by Nicola Peluchetti

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

通过这种方式,您将拥有一个对象,该对象将“数据”中包含的“id”作为属性,并将相对名称作为这些属性的值