javascript foreach on object keys code example

Example 1: javascript object keys foreach

var lunch = {
	sandwich: 'ham',
	snack: 'chips',
	drink: 'soda',
	desert: 'cookie',
	guests: 3,
	alcohol: false,
};

Object.keys(lunch).forEach(function (item) {
	console.log(item); // key
	console.log(lunch[item]); // value
});

// returns "sandwich", "ham", "snack", "chips", "drink", "soda", "desert", "cookie", "guests", 3, "alcohol", false

Example 2: for key value in object javascript

for (const [key, value] of Object.entries(object1)) {
  console.log(`${key}: ${value}`);
}