Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Foreach value in array to string

Looking for some help in JS. I have an array of array's

var totalOrder = []
function CafeService(meal, starter, main, dessert){//takes value from text box input
var customerOrder = [meal, starter, main, dessert]

totalOrder.push(customerOrder ); 
}

This is populating correctly.There can be a unlimited amount of orders. I want to check through the order before sending to the kitchen. How can I put each index in the array into strings e.g. to populate the below:

var mealTime;
var mealStarter;
var mealMain;
var mealDessert;

I expect I need to do this with a for each?

foreach (customerOrder in totalOrder){
    var mealTime; //how to populate
    var mealStarter;
    var mealMain;
    var mealDessert;
}

EDIT Total Order with one customers order:

var totalOrder = ["Breakfast","Coffee","Toast","Apple"]
like image 768
Phil3992 Avatar asked Sep 16 '26 22:09

Phil3992


1 Answers

You can simply affect those variables using their indexes :

var totalOrder = [];

function CafeService(meal, starter, main, dessert) {
  var customerOrder = [meal, starter, main, dessert];
  totalOrder.push(customerOrder);
}

CafeService('1', 'Salad', 'Hamburger', 'Soda');
CafeService('1', 'Salad', 'Hamburger', 'Soda');
CafeService('1', 'Salad', 'Hamburger', 'Soda');

totalOrder.forEach(function (customerOrder) {
  var mealTime = customerOrder[0];
  var mealStarter = customerOrder[1];
  var mealMain = customerOrder[2];
  var mealDessert = customerOrder[3];
  
  console.log(mealTime, mealStarter, mealMain, mealDessert);
});

Or, if you use ES6 syntax, you can use destructuring assignment :

var totalOrder = [];

function CafeService(meal, starter, main, dessert) {
  var customerOrder = [meal, starter, main, dessert];
  totalOrder.push(customerOrder);
}

CafeService('1', 'Salad', 'Hamburger', 'Soda');
CafeService('1', 'Salad', 'Hamburger', 'Soda');
CafeService('1', 'Salad', 'Hamburger', 'Soda');

totalOrder.forEach(function (customerOrder) {
  var [mealTime, mealStarter, mealMain, mealDessert] = customerOrder;
  
  console.log(mealTime, mealStarter, mealMain, mealDessert);
});

Note I used .forEach instead of for...in for reasons; classic for-loop is also a valid option. You could use for...of with ES6.

like image 69
Serge K. Avatar answered Sep 19 '26 11:09

Serge K.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!