如何遍历&将值对添加到JSON对象? [英] How to loop through & add pairs of values to JSON object?

查看:90
本文介绍了如何遍历&将值对添加到JSON对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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'
},

这样,当我遍历数据时,我会将更多数据推送到数组的末尾.当前,仅显示'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);

据我所知,JavaScript似乎不喜欢使用变量作为标识符,即我不能这样做:jsonObj.push({data[i].id:data[i].name});

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});

为了使选择框按需工作,我该如何创建所需的JSON对象?

How might I go about creating the kind of JSON object I need, in order to get the Select Box working as needed?

推荐答案

我认为数组和对象之间存在很多混乱.您可以这样做:

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;
}

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

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

这篇关于如何遍历&amp;将值对添加到JSON对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆