Home > Blockchain >  Item cant be accessed from multidimensional array
Item cant be accessed from multidimensional array

Time:09-22

I am trying to fetch DishId from below multidimensional array but I am not able to achieve it. Below is the code details.

count = 0;

for (j = 0; j < OrderDishes.length; j  ) { 
    for (k = 0; k < OrderDishes[j].length; k  ) {  
           
        dishId.push(OrderDishes[k].DishId);
        count = count   1;
        if(count == OrderDishes[j].length){
            console.log(dishId);
            return res.json({
                success: 1
            });
        }
         
    } 

}

OrderDishes is below Array :

[ [ { DishId: 43,
      DishName: 'Kuchvi Biryani',
      Spicy: 2,
      UnitPrice: '6.99',
      Qty: 5,
      DishTotal: '34.95' } ],
      
  [ { DishId: 41,
      DishName: 'Dum Biryani',
      Spicy: 2,
      UnitPrice: '6.99',
      Qty: 5,
      DishTotal: '34.95' },
    { DishId: 42,
      DishName: 'Tysoon Biryani',
      Spicy: 2,
      UnitPrice: '6.99',
      Qty: 5,
      DishTotal: '34.95' } ] ]

When i run, i am getting 43 and 41 , instead i was looking for 43, 41 and 42

CodePudding user response:

You are getting only 43 and 41 because of the count condition. The length of your outer array is 2. dishId 43 is one array and dish 41 and 42 are in a second array. As soon as count reaches 2, it stops.

Try to move your count and if condition out of the inner loop.

const OrderDishes = [
  [{
    DishId: 43,
    DishName: 'Kuchvi Biryani',
    Spicy: 2,
    UnitPrice: '6.99',
    Qty: 5,
    DishTotal: '34.95'
  }],

  [{
      DishId: 41,
      DishName: 'Dum Biryani',
      Spicy: 2,
      UnitPrice: '6.99',
      Qty: 5,
      DishTotal: '34.95'
    },
    {
      DishId: 42,
      DishName: 'Tysoon Biryani',
      Spicy: 2,
      UnitPrice: '6.99',
      Qty: 5,
      DishTotal: '34.95'
    }
  ]
]

count = 0;
let dishId = []

for (j = 0; j < OrderDishes.length; j  ) {
  for (k = 0; k < OrderDishes[j].length; k  ) {
    dishId.push(OrderDishes[j][k].DishId);
  }
  count  ;
  if (count === OrderDishes.length) {
    console.log('dishID: ', dishId);

  }
}

CodePudding user response:

try dishId.push(OrderDishes[j][k].DishId); , you are using multidimensional array , so , you need to get access to a cell by col id and row id.

  • Related