计算并循环遍历对象内的多个数组

时间:2016-10-30 05:36:09

标签: javascript arrays

我基本上只是尝试遍历一系列数组(动态创建)并在控制台中输出结果。调试器告诉我this.allitems[i]未定义。如何遍历allItems对象中的每个数组?

var warehouse = {
  allItems: {
    shirts:[],
    shorts:[]
  },

 // Counts how many arrays are in the object 
 countArraysInAllItems: function(obj){
    var size = 0,key;
    for(key in obj){
      if(obj.hasOwnProperty(key)) size++;
    }
    return size;
  },

  // Display the items from the arrays (in no particular order)
  displayItems: function(){
    var allItemsLength = this.countArraysInAllItems(this.allItems);

    for(var i=0; i<allItemsLength; i++){
      var itemSubArray = this.allItems[i];

      for(var j=0; j<itemSubArray.length; j++){
        var itemType = this.itemSubArray[j].itemType;
        var itemName = this.itemSubArray[j].itemName;
        var itemQuantity = this.itemSubArray[j].itemQuantity;

        console.log('Type:' + itemType + '\n' + 
                  'Name: ' + itemName + '\n' +  
                  'Qty:' + itemQuantity);
        }
      }
    }

6 个答案:

答案 0 :(得分:1)

问题是JS中的传统for循环可用于循环遍历数组而不是对象。如果你考虑一下,它就有意义了 - 对象中的属性本身并不是特定的索引

您正在寻找的是for...in循环 - 您已经在使用它进行计数,但由于某种原因,您将在后续循环中放弃它。

尝试这样的事情 - 我无法使用不完整的代码/数据集对其进行测试,但我认为它将更接近您想要实现的目标(您甚至可能不需要{{1} }方法了):

countArraysInAllItems

PS - 我做了一些其他的小改动 - 首先,我将所有var warehouse = { allItems: { shirts: [], shorts: [] }, // Counts how many arrays are in the object countArraysInAllItems: function(obj) { var size = 0, key; for (key in obj) { if (obj.hasOwnProperty(key) && Array.isArray(obj[key])) { size++; } } return size; }, // Display the items from the arrays (in no particular order) displayItems: function() { var allItemsLength = this.countArraysInAllItems(this.allItems); var key; var j; var itemSubArray; var itemType; var itemName; var itemQuantity; for (key in this.allItems) { if (obj.hasOwnProperty(key) && Array.isArray(obj[key])) { itemSubArray = obj[key]; for (j = 0; j < itemSubArray.length; j++) { itemType = this.itemSubArray[j].itemType; itemName = this.itemSubArray[j].itemName; itemQuantity = this.itemSubArray[j].itemQuantity; console.log('Type:' + itemType + '\n' + 'Name: ' + itemName + '\n' + 'Qty:' + itemQuantity); } } } } }; 声明移到功能范围的顶部以管理hoisting,并且还包括检查以确保事实上,var对象的属性是一个数组(以防万一你计划在对象上存储其他东西)。

答案 1 :(得分:1)

正如其他答案所述,allItems是一个对象,因此您不能将其作为数组进行迭代。

这是我的解决方案,有2个for..in循环,使代码更简洁:

var warehouse = {
  allItems: {
    shirts:[
      {
        itemType: "type1",
        itemName: "shirt1",
        itemQuantity: 1
      },
      {
      itemType: "type2",
      itemName: "shirt2",
      itemQuantity: 10
    }
    ],
    shorts:[
      {
        itemType: "type3",
        itemName: "short1",
        itemQuantity: 4
      }
    ]
  },

// Counts how many arrays are in the object 
countArraysInAllItems: function(obj){
    var size = 0,key;
    for(key in obj){
      if(obj.hasOwnProperty(key)) size++;
    }
    return size;
  },

  // Display the items from the arrays (in no particular order)
  displayItems: function(){
    // this variable is not useful right now
    var allItemsLength = this.countArraysInAllItems(this.allItems);

    for(var i in this.allItems){
      var itemSubArray = this.allItems[i];

      for(var j in itemSubArray){
        var itemType = itemSubArray[j].itemType;
        var itemName = itemSubArray[j].itemName;
        var itemQuantity = itemSubArray[j].itemQuantity;

        console.log('Type:' + itemType + '\n' + 
                  'Name: ' + itemName + '\n' +  
                  'Qty:' + itemQuantity);
      }
    }
  }
}

答案 2 :(得分:1)

如果你结婚使用for ..循环,你可以这样做:

var warehouse = {
  allItems: {
    shirts:{itemType:"type1", itemName:"name1", itemQuantity:"qty1"},
    shoes:{itemType:"type2", itemName:"name2", itemQuantity:"qty2"}
  },

  // Display the items from the arrays (in no particular order)
  displayItems: function(){
      for (var item in this.allItems) {
        console.log(item);
        var itemType = this.allItems[item].itemType;
        var itemName = this.allItems[item].itemName;
        var itemQuantity = this.allItems[item].itemQuantity;
        console.log('Type: ' + itemType + '\n' +
                  'Name: ' + itemName + '\n' +
                  'Qty: ' + itemQuantity);
      }
    }
}

warehouse.displayItems();

Othewrwise,您可以(并且应该)按照其他人的建议迭代Object.keys()。

答案 3 :(得分:0)

您可以使用for..in循环。 allTtems属性的第一个循环和数组衬衫和短裤的另一个嵌套循环:

var warehouse = {
  allItems: {
    shirts:[1,2,3,],
    shorts:[10,11,12]
  }
};
for (var item in warehouse)
  for (var element in warehouse[item])
     console.log(warehouse[item][element]);
// [ 1, 2, 3 ]
// [ 10, 11, 12 ]

答案 4 :(得分:0)

您可以使用

    Object.keys(this.allItems).forEach(item => {
      console.log(item);
    });

更准确的答案

  const warehouse = {
    allItems: {
        shirts: [
            {
                itemType: '1',
                itemName: '2',
                itemQuantity: '3',
            }
        ],
        shorts: [
            {
                itemType: '5',
                itemName: '6',
                itemQuantity: '7',
            }
        ]
    },

    // Display the items from the arrays (in no particular order)
    displayItems: function() {
        Object.keys(this.allItems).forEach(items => {
            Object.keys(this.allItems[items]).forEach(item => {
                const {itemType, itemName, itemQuantity} = this.allItems[items][item];
                console.log(itemType, itemName, itemQuantity);
            });
        });
    }
  }

答案 5 :(得分:0)

使用Object.keys()Array.prototype.forEach()迭代对象。然后使用forEach()迭代每个数组:

&#13;
&#13;
var warehouse = {
  allItems: {
    shirts: [{
      itemType: "type1",
      itemName: "shirt1",
      itemQuantity: 1
    }, {
      itemType: "type2",
      itemName: "shirt2",
      itemQuantity: 10
    }],
    shorts: [{
      itemType: "type3",
      itemName: "short1",
      itemQuantity: 4
    }]
  },
  displayItems: function() {
    var items = this.allItems;
    Object.keys(items).forEach(function(key) {
      items[key].forEach(function(item) {
        console.log('Type:' + item.itemType + '\n' +
          'Name: ' + item.itemName + '\n' +
          'Qty:' + item.itemQuantity);
      });
    });
  }
};

warehouse.displayItems();
&#13;
&#13;
&#13;

相关问题