循环遍历对象及其数组
Loop through object and its array
假设我有一个包含几个对象的数组,如下所示:
{
"firstname": John,
"lastname": "Doe",
"numbers": [{
"id": 1,
"value": "123"
}, {
"id": 2,
"value": "123"
}],
}, ...
我如何循环通过这些对象,同时也循环通过他们的"数字"属性?
var input = {
"firstname": "John",
"lastname": "Doe",
"numbers": [{
"id": 1,
"value": "123"
}, {
"id": 2,
"value": "123"
}]
}
for (var key in input) {
if (key === "numbers") {
for (var i=0; i < input[key].length; i++) {
console.log(input[key][i]);
}
} else {
console.log(key + ":" + input[key])
}
}
嵌套循环:
var input = [{
"firstname": John,
"lastname": "Doe",
"numbers": [{
"id": 1,
"value": "123"
}, {
"id": 2,
"value": "123"
}],
}]
input.forEach(function(item) {
item.numbers.forEach(function(number) {
console.log(number.id, number.value)
}
}
这个使用递归,所以即使模式不相同也可以工作:
function looopAllTheThings(theThings, theCallback, depth){
if(undefined===depth) depth = 0;
if(typeof theThings == "object"){
for(var p in theThings)
if(theThings.hasOwnProperty(p))
if("object" == typeof theThings[p] ||
"array" == typeof theThings[p])
looopAllTheThings(theThings[p], theCallback, (depth+1));
else theCallback(p, theThings[p], depth);
}else if(typeof theThings == "array"){
for(var i=0; i<theThings.length; i++)
if("object" == typeof theThings[i] ||
"array" == typeof theThings[i])
looopAllTheThings(theThings[i], theCallback, (depth+1));
else theCallback(p, theThings[i], depth);
}else{
theCallback(null, theThings, depth);
}
}
像这样使用:
looopAllTheThings(data, function(key, value, depth){
document.getElementById('out').innerHTML += ("-".repeat(depth))+" "+key+" = "+value+"<br>";
});
这里有一个小提琴:https://jsfiddle.net/2o2Lyayj/
相关文章:
- 将数组对象传递到struts2中的操作类
- 如何使用jquery返回php-json数组对象
- 从其名称获取javascript数组对象
- 值未与数组对象绑定
- 如何按数组/对象值的倍数过滤对象数组
- 在表中显示数组对象
- 在数组对象中分组
- 将第二个或多个数组推送到数组对象 AngularJS 中
- 重新排列 JavaScript 数组/对象
- 键上的javascript数组对象过滤器
- handontable:在不更改数据数组/对象的情况下隐藏某些列
- 用于跟踪购物车可用性的Javascript数组/对象/哈希表
- 重建有角度的java脚本数组对象
- 对JSON数组对象进行排序
- 连接与数组对象相关的文本:方式和位置
- 哪些浏览器和版本支持将常见的类数组对象直接传递到fn.apply()
- 如何使用Handlebars循环数组对象和模板
- 是否可以引用JS数组/对象中的另一个元素
- Javascript中的名称索引-数组/对象
- 数组长度不等于数组对象