key array value object foreach in js code example

Example 1: javascript foreach object keys

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: javascript foreach object key

const obj = {
  name: 'Jean-Luc Picard',
  rank: 'Captain'
};

// Prints "name Jean-Luc Picard" followed by "rank Captain"
Object.keys(obj).forEach(key => {
  console.log(key, obj[key]);
});