2016-08-30 102 views
-3

说,我有几个对象的数组,看起来像这样:遍历对象及其阵列

{ 
    "firstname": John, 
    "lastname": "Doe", 
    "numbers": [{ 
     "id": 1, 
     "value": "123" 
    }, { 
     "id": 2, 
     "value": "123" 
    }], 
}, ... 

我怎么遍历这些对象的同时,也通过他们的“数字”属性循环?

+0

你有一个'for'循环,然后里面有,你有另一个'for'循环。如果你显示你的代码,你可能会得到更具体的答案。 –

回答

1

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]) 
 
     } 
 
    }

1

嵌套循环:

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) 
    } 
} 
1

这一个使用递归所以如果该模式是不一样的,它仍然工作:

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/