2016-08-30 6 views
-3

は、私はこのように見て、複数のオブジェクトの配列を持っていると言う:オブジェクトをループし、その配列は

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

をどのようにも彼らの「数字」プロパティをループしながら、これらのオブジェクトからiループのですか?

+0

あなたは1 '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

それはパターンが同じでない場合であっても動作しますので、この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/

関連する問題