@@ -10,20 +10,49 @@ function invert(obj) {
10
10
const invertedObj = { } ;
11
11
12
12
for ( const [ key , value ] of Object . entries ( obj ) ) {
13
- invertedObj . key = value ;
13
+ invertedObj [ value ] = key ;
14
14
}
15
15
16
16
return invertedObj ;
17
17
}
18
18
19
+ const profile = {
20
+ name : "Alex" ,
21
+ age : 19 ,
22
+ occupation : "student" ,
23
+ } ;
24
+
25
+ //console.log(Object.entries(profile));
26
+ //const result = invert(profile);
27
+ //console.log(result);
28
+
29
+ // console.log(invert({ a: 1, b: 2 }));
30
+
19
31
// a) What is the current return value when invert is called with { a : 1 }
32
+ // {key: 1}
20
33
21
34
// b) What is the current return value when invert is called with { a: 1, b: 2 }
35
+ // { key: 2 }
22
36
23
37
// c) What is the target return value when invert is called with {a : 1, b: 2}
38
+ // {1 : a, 2: b}
24
39
25
40
// c) What does Object.entries return? Why is it needed in this program?
41
+ // It returns e.g. [ [ 'name', 'Alex' ], [ 'age', 19 ], [ 'occupation', 'student' ] ] array of arrays
42
+ // It is needed because we want to iterate through an array to get key and values pars for new object.
26
43
27
44
// d) Explain why the current return value is different from the target output
45
+ // The current return value is different from the target output because the function
46
+ // is working improperly. First of all, the key should be taken on brackets to make possible
47
+ // to read every key name-value and value in every pair in subarray.
48
+ // invertedObj.key = value: This is a direct assignment. It treats "key" as a literal string
49
+ // and creates or updates a property named "key" on the invertedObj object, setting its value
50
+ // to the value of the value variable.
51
+ // invertedObj[key] = value: This uses bracket notation. It evaluates the key variable and uses
52
+ // its value (which is a string) as the property name on invertedObj.
53
+ // Secondly, change the key and value places for new object creation statement
54
+ // 'invertedObj[value] = key;' to get swapping the keys and values in the new object.
28
55
29
56
// e) Fix the implementation of invert (and write tests to prove it's fixed!)
57
+
58
+ module . exports = invert ;
0 commit comments