Javascript 如何用循环构建一个json对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11278161/
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
How to build a json object with a loop?
提问by RJP
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.
我正在尝试遍历许多项目,并创建一个 json 对象。每个循环都应该是对象上的一个新项目,但我在做这件事时遇到了一些问题。似乎只添加了一组项目,而不是多个项目。
Here is my code:
这是我的代码:
jsonObj = {}
rows.each(function (index) {
jsonObj["id"] = $this.find('.elementOne').val();
jsonObj["name"] = $this.find('.elementTwo').text();
});
Here is what my json looks like:
这是我的 json 的样子:
{
id: "3"
name: "Stuff"
},
Here is what I am trying to do:
这是我想要做的:
{
id: "1"
name: "Stuff"
},
{
id: "2"
name: "Stuff"
},
{
id: "3"
name: "Stuff"
}
回答by Quentin
There is no JSON here. Please don't confuse:
这里没有 JSON。请不要混淆:
- A JavaScript object (a data structure)
- A JavaScript object literal (code to create such a data structure)
- JSON (a data format based on a subset of object literal notation)
- 一个 JavaScript 对象(一种数据结构)
- JavaScript 对象字面量(创建此类数据结构的代码)
- JSON(一种基于对象文字符号子集的数据格式)
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.
如果您想要一个有序的对象列表(或任何其他类型的 JavaScript 数据结构),请使用数组。数组有一个push
方法。
var myData = [];
rows.each(function (index) {
var obj = {
id: $this.find('.elementOne').val(),
name: $this.find('.elementTwo').text()
};
myData.push(obj);
});
回答by gdoron is supporting Monica
You override the object instead of adding it a new value each iteration.
您可以覆盖该对象,而不是在每次迭代时为其添加一个新值。
Fixed codeusing an array:
使用数组的固定代码:
jsonObj = [];
rows.each(function(index) {
jsonObj.push({
'id': $this.find('.elementOne').val(),
'name': $this.find('.elementTwo').text()
});
});?
回答by Anurag
What you want is an array of objects. When you try to write the same property on the same object multiple times, it gets overwritten which is why you're seeing id
and name
contain values for the last iteration of the loop.
你想要的是一个对象数组。当您尝试在同一个对象上多次写入相同的属性时,它会被覆盖,这就是您看到id
并name
包含循环最后一次迭代的值的原因。
Although you haven't tagged the question with jQuery, it does look like jQuery, so here's a solution:
虽然你没有用 jQuery 标记这个问题,但它看起来确实像 jQuery,所以这里有一个解决方案:
I've taken the liberty to change $this
to this
because $this
seems to be referring to the same object in each iteration, which is now what you may want (methinks)
我冒昧地更改$this
为,this
因为$this
似乎在每次迭代中都指的是同一个对象,这就是您现在可能想要的(我认为)
var myArray = rows.map(function() {
return {
id: $(this).find('.elementOne').val(),
name: $(this).find('.elementTwo').text()
};
});
回答by Atanas Kovachev
You can do it like this with jquery. The function will expect form elements of type input. It will iterate over thr passed form and it will collect each input name and value and it will create a json object like
你可以用 jquery 来做到这一点。该函数需要输入类型的表单元素。它将遍历 thr 传递的表单,并收集每个输入名称和值,并创建一个 json 对象,如
Exmple:
例子:
HTML
HTML
<form action="" method="post" id="myForm">
<input type="text" name="field1" value="I am value of field 1"/>
<input type="text" name="field2" value="I am value of field 2"/>
</form>
Javascript
Javascript
function buildObject(form) {
var jsonObject = [],
tempObj = {};
$(form).find("input:not(input[type='submit'])").each(function() {
tempObj[$(this).attr("name")] = $(this).val();
});
jsonObject.push(tempObj);
return jsonObject[0];
}
buildObject($("#myForm"));
//Will produce
jsonObj = {
field1 : "I am value of field 1",
field2 : "I am value of field 2"
}
回答by Utkanos
This is because you're merely overwriting the same properties of your object, id
and name
, each time. You need to be making a sub-object for each, then push it into the master object (which I've converted to array, since it's non-associative).
这是因为您只是每次都覆盖对象的相同属性id
和name
。您需要为每个对象创建一个子对象,然后将其推入主对象(我已将其转换为数组,因为它是非关联的)。
var jsonObj = []
rows.each(function (index) {
var temp_obj = {};
temp_obj["id"] = $this.find('.elementOne').val();
temp_obj["name"] = $this.find('.elementTwo').text();
jsonObj.push(temp_obj);
});
[EDIT] - as Mark Eirich's answer shows, the temp_obj
is unnecessary - you could push an anonymous object instead, but I defined temp_obj
just to make it crystal clear what's happening.
[编辑] - 正如 Mark Eirich 的回答所示,这temp_obj
是不必要的 - 你可以推送一个匿名对象,但我定义temp_obj
只是为了清楚地说明正在发生的事情。
Also read Quentin's very good points re: common confusion between JavaScript objects and JSON.
另请阅读 Quentin 的非常好的观点:JavaScript 对象和 JSON 之间的常见混淆。
回答by Mark Eirich
var jsonObj = [];
rows.each(function(index) {
jsonObj.push({
id: $this.find('.elementOne').val(),
name: $this.find('.elementTwo').text()
});
});