1myObject ={a:1,b:2,c:3}
2
3//es6
4Object.entries(myObject).forEach(([key, value]) => {
5 console.log(key , value); // key ,value
6});
7
8//es7
9Object.keys(myObject).forEach(key => {
10 console.log(key , myObject[key]) // key , value
11})
1const obj = {
2 name: 'Jean-Luc Picard',
3 rank: 'Captain'
4};
5
6// Prints "name Jean-Luc Picard" followed by "rank Captain"
7Object.keys(obj).forEach(key => {
8 console.log(key, obj[key]);
9});
1var person={
2 first_name:"johnny",
3 last_name: "johnson",
4 phone:"703-3424-1111"
5};
6for (var property in person) {
7 console.log(property,":",person[property]);
8}
1/* Answer to: "foreach object javascript" */
2
3const games = {
4 "Fifa": "232",
5 "Minecraft": "476"
6 "Call of Duty": "182"
7};
8
9Object.keys(games).forEach((item, index, array) => {
10 let msg = `There is a game called ${item} and it has sold ${games[item]} million copies.`;
11 console.log(msg);
12});
13
14/*
15 The foreach statement can be used in many ways and with object can make
16 development a lot easier.
17
18 A link for for more information on this can be found below and in the source:
19 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
20*/
1const object1 = {
2 a: 'somestring',
3 b: 42
4};
5for (let [key, value] of Object.entries(object1)) {
6 console.log(`${key}: ${value}`);
7}
8// expected output:
9// "a: somestring"
10// "b: 42"
11// order is not guaranteed