如何用循环构建一个json对象? [英] How to build a json object with a loop?

查看:122
本文介绍了如何用循环构建一个json对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试遍历许多项目,并创建一个json对象。每个循环应该是对象上的一个新项目,但我遇到了一些问题。似乎只添加了一组项目,而不是多项。

I'm trying to loop through a number of items, and create a json object. Each loop should be a new item on the object, but I'm having some issues doing it. It seems that only one set of items gets added, instead of multiple ones.

这是我的代码:

jsonObj = {}
rows.each(function (index) {
    jsonObj["id"] = $this.find('.elementOne').val();
    jsonObj["name"] = $this.find('.elementTwo').text();

});

这是我的json的样子:

Here is what my json looks like:

{
    id: "3"
    name: "Stuff"
},

以下是我要做的事情:

{
    id: "1"
    name: "Stuff"
},
{
    id: "2"
    name: "Stuff"
},
{
    id: "3"
    name: "Stuff"
}


推荐答案

这里没有JSON。请不要混淆:

There is no JSON here. Please don't confuse:


  • JavaScript对象(数据结构)

  • 一个JavaScript对象literal(用于创建此类数据结构的代码)

  • JSON(基于对象文字表示法子集的数据格式)

如果你想要一个有序的对象列表(或任何其他类型的JavaScript数据结构),那么使用一个数组。数组有一个 push 方法。

If you want an ordered list of objects (or any other kind of JavaScript data structure) then use an array. Arrays have a push method.

var myData = [];
rows.each(function (index) {
    var obj = { 
        id: $this.find('.elementOne').val(),
        name: $this.find('.elementTwo').text()
    };
    myData.push(obj);
});

这篇关于如何用循环构建一个json对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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