qua1ity qua1ity - 3 months ago 7
Javascript Question

Loop through object and its array

Say i have an array with several objects, looking like this:

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


How do i loop through these objects while also looping through their "numbers" property?

Answer

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

Comments