1// object to loop through
2let obj = { first: "John", last: "Doe" };
3
4// loop through object and log each key and value pair
5//ECMAScript 5
6Object.keys(obj).forEach(function(key) {
7 console.log(key, obj[key]);
8});
9
10//ECMAScript 6
11for (const key of Object.keys(obj)) {
12 console.log(key, obj[key]);
13}
14
15//ECMAScript 8
16Object.entries(obj).forEach(
17 ([key, value]) => console.log(key, value)
18);
19
20// OUTPUT
21/*
22 first John
23 last Doe
24*/
1for (var property in object) {
2 if (object.hasOwnProperty(property)) {
3 // Do things here
4 }
5}
6
1var obj = { first: "John", last: "Doe" };
2
3Object.keys(obj).forEach(function(key) {
4 console.log(key, obj[key]);
5});
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}
1Object.entries(obj).forEach(
2 ([key, value]) => console.log(key, value)
3);
4
5// Loop using forEach
6arr.forEach((item, index) => {
7 // TODO
8})
9
10// Loop using for...of
11for (const item of arr) {
12 await something()
13}
14
15// Clone new array (not changing the old one)
16const arr = [1,2,3]
17const newArray = arr.map(item => item * 2)
18console.log(newArray)
19
20// Filter array by condition
21const arr = [1,2,3,1]
22const newArray = arr.filter(item => {
23 if (item === 1) { return item }
24})
25console.log(newArray)
26
27// Join array
28const arr1 = [1,2,3]
29const arr2 = [4,5,6]
30const arr3 = [...arr1, ...arr2]
31console.log(arr3)
32
33// Get a property of object
34const { email, address } = user
35console.log(email, address)
36
37// Copy object/array
38const obj = { name: 'my name' }
39const clone = { ...obj }
40console.log(obj === clone)
1const point = {
2 x: 10,
3 y: 20,
4};
5
6for (const [axis, value] of Object.entries(point)) {
7 console.log(`${axis} => ${value}`);
8}
9
10/** prints:
11 * x => 10
12 * y => 20
13 */
1var p = {
2 "p1": "value1",
3 "p2": "value2",
4 "p3": "value3"
5};
6
7for (var key in p) {
8 if (p.hasOwnProperty(key)) {
9 console.log(key + " -> " + p[key]);
10 }
11}