/
index.js
101 lines (76 loc) · 2.29 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// EXAMPLE 1 - Update all the Values in an Object in JavaScript
const obj = {
country: 'Chile',
city: 'Santiago',
address: 'Example',
name: 'bobby hadz',
};
Object.keys(obj).forEach(key => {
obj[key] = '';
});
// 👇️ { country: '', city: '', address: '', name: '' }
console.log(obj);
// ------------------------------------------------------------------
// // EXAMPLE 2 - Conditionally update the values in an object
// const obj = {
// name: 'bobby hadz',
// num1: 9,
// num2: 19,
// num3: 29,
// };
// Object.keys(obj).forEach((key, index) => {
// if (typeof obj[key] === 'number' && obj[key] > 10) {
// obj[key] = 0;
// }
// });
// // 👇️ { name: 'bobby hadz', num1: 9, num2: 0, num3: 0 }
// console.log(obj);
// ------------------------------------------------------------------
// // EXAMPLE 3 - Update all the Values in an Object without Mutation
// const obj = {
// country: 'Chile',
// city: 'Santiago',
// address: 'Example',
// name: 'bobby hadz',
// };
// const newObj = Object.keys(obj).reduce((accumulator, key) => {
// return {...accumulator, [key]: ''};
// }, {});
// // { country: '', city: '', address: '', name: '' }
// console.log(newObj);
// // {
// // country: 'Chile',
// // city: 'Santiago',
// // address: 'Example',
// // name: 'bobby hadz'
// // }
// console.log(obj);
// ------------------------------------------------------------------
// // EXAMPLE 4 - Conditionally update the values in an object using reduce()
// const obj = {
// name: 'bobby hadz',
// num1: 9,
// num2: 19,
// num3: 29,
// };
// const newObj = Object.keys(obj).reduce((accumulator, key) => {
// if (typeof key[obj] === 'number' && key[obj] > 10) {
// return {...accumulator, [key]: 0};
// }
// return {...accumulator, [key]: obj[key]};
// }, {});
// // 👇️ { name: 'bobby hadz', num1: 9, num2: 19, num3: 29 }
// console.log(newObj);
// ------------------------------------------------------------------
// // EXAMPLE 5 - Update all the Values in an Object using `for...of`
// const obj = {
// country: 'Chile',
// city: 'Santiago',
// address: 'Example',
// name: 'bobby hadz',
// };
// for (const key of Object.keys(obj)) {
// obj[key] = '';
// }
// // 👇️ { country: '', city: '', address: '', name: '' }
// console.log(obj);