循环遍历对象及其数组

时间:2016-08-30 19:26:41

标签: javascript jquery

假设我有一个包含多个对象的数组,如下所示:

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

如何在循环浏览“数字”属性的同时循环遍历这些对象?

3 个答案:

答案 0 :(得分: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)



    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])
       }
    }
&#13;
&#13;
&#13;

答案 2 :(得分: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/

相关问题