如何在 javascript for 循环中创建一个 json 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29658961/
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 create a json object in javascript for loop
提问by Gopi Nath
I would like to create a JSON object inside a for loop using javascript. I am expecting an result something like this:
我想使用 javascript 在 for 循环中创建一个 JSON 对象。我期待这样的结果:
{
"array":[
{
"value1":"value",
"value2":"value"
},
{
"value1":"value",
"value2":"value"
}
]
}
Can somebody help me on how to achieve this result in javascript ?
有人可以帮助我如何在 javascript 中实现这个结果吗?
回答by S Farron
Instead of creating the JSON in the for-loop, create a regular JavaScript object using your for-loops and use JSON.stringify(myObject) to create the JSON.
不是在 for 循环中创建 JSON,而是使用 for 循环创建常规 JavaScript 对象并使用 JSON.stringify(myObject) 创建 JSON。
var myObject = {};
for(...) {
myObject.property = 'newValue';
myObject.anotherProp = [];
for(...) {
myObject.anotherProp.push('somethingElse');
}
}
var json = JSON.stringify(myObject);
回答by QBM5
var loop = [];
for(var x = 0; x < 10; x++){
loop.push({value1: "value_a_" + x , value2: "value_b_" + x});
}
JSON.stringify({array: loop});
回答by avenet
This code produces what you need:
此代码生成您需要的内容:
var result = {"array": []};
for(var i = 0; i < 2; i++){
var valueDict = {};
for(var j = 0; j < 2; j++){
valueDict["value" + (j+1).toString()] = "value";
}
result["array"].push(valueDict);
}
It uses the push functionto add items to the list, and the indexer [] notationnotation to modify the entries on the object prototype.
它使用push 函数将项目添加到列表中,并使用indexer [] 表示法修改对象原型上的条目。
Hope it helps,
希望能帮助到你,

