javascript foreach object in array code example

Example 1: javascript foreach object

const list = {
  key: "value",
  name: "lauren",
  email: "[email protected]",
  age: 30
};

// Object.keys returns an array of the keys
// for the object passed in as an argument.

Object.keys(list).forEach(val => {
  let key = val;
  let value = list[val];
  console.log(`${key} : ${value}`);
});

// Returns:
// "key : value"
// "name : lauren";
// "email : [email protected]"
// "age : 30"

Example 2: javascript foreach index

users.forEach((user, index)=>{
	console.log(index); // Prints the index at which the loop is currently at
});

Example 3: foreach jas

const array1 = ['a', 'b', 'c'];

array1.forEach(element => console.log(element));

Example 4: for each

const array1 = ['a', 'b', 'c'];

array1.forEach(element => console.log(element));

// expected output: "a"
// expected output: "b"
// expected output: "c"

Example 5: mdn foreach

arr.forEach(callback(currentValue [, index [, array]])[, thisArg])

Example 6: javascript foreach object

function logArrayElements(element, index, array) {
  console.log('a[' + index + '] = ' + element)
}

// Notice that index 2 is skipped, since there is no item at
// that position in the array...
[2, 5, , 9].forEach(logArrayElements)
// logs:
// a[0] = 2
// a[1] = 5
// a[3] = 9

Tags:

Php Example