[英]How do I loop through a JSON object that contains arrays?
How would I loop through this correctly? 我将如何正确循环?
{names:['oscar','bill','brad'],ages:['20','25','18']}
So i'd basically get the output: 所以我基本上会得到输出:
names: oscar
ages: 20
names: bill
ages: 25
names: brad
ages: 18
Yes I know its a for...in loop but I just can't figure out how to get this output. 是的,我知道它的for ... in循环,但我只是想不出如何获得此输出。
maybe 也许
for (var i = 0, len = obj.names.length; i < len; ++i) {
var name = obj.names[i];
var age = obj.ages[i];
// ... whatever
}
where "obj" is your JSON object 其中“ obj”是您的JSON对象
Just a simple suggestion. 只是一个简单的建议。 It seems to me, implementation bellow would be better for you
在我看来,实施波纹管对您会更好
{ people:[{name:'oscar',age:20},{...},{...}] }
To loop through this 循环浏览
var a = { people:[{name:'oscar',age:20}] };
var array = a.people
for(element in array){
console.log(array[element].name + ',' + array[element].age);
}
we have our main object in variable a and inside we have our array in people attribute of our object. 我们的主要对象位于变量a中,而内部的数组位于我们对象的people属性中。 Array have our person objects inside.
数组内部有我们的person对象。 so first person in our list is a.people[0].name does that help?
所以我们列表中的第一人称a.people [0] .name有帮助吗? as you need to use closure with this array you can check this blog post.
因为您需要对此数组使用闭包,所以可以查看此博客文章。 http://yilmazhuseyin.wordpress.com/2010/07/19/closure-in-javascript-part-3/
http://yilmazhuseyin.wordpress.com/2010/07/19/closure-in-javascript-part-3/
var data = {names:['oscar','bill','brad'],ages:['20','25','18']}
function loop() {
var arrNames = data.names;
var ages = data.ages;
var str = [];
for(var i = 0, len = arrNames.length; i < len; i++) {
str.push("\nnames: " + arrNames[i] + "\nages:" + ages[i]);
}
alert(str.join(""));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.