循环遍历对象及其数组

Loop through object and its array

本文关键字:数组 对象 遍历 循环      更新时间:2023-09-26

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

{
  "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/