-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobjectQuestion.js
More file actions
48 lines (46 loc) · 865 Bytes
/
objectQuestion.js
File metadata and controls
48 lines (46 loc) · 865 Bytes
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
/*
* Question: Write a function that takes 3 args -> object,
* keyPath and value.
* The function has to set the value of keyPath on the
* object and return the object.
*/
// the object arg
const a = {
c: {
d: {
e: {
weight: "120",
unit: "KG",
},
name: "_name_",
},
},
};
// the keyPath arg
const keyPath = "c.d.e.unit";
// the value arg
const value = "LB";
// the return value
/*
{
c: {
d: {
e: {
weight: '120',
unit: 'LB'
},
name: '_name_'
}
}
}
*/
function key(a, keyPath, value) {
const keys = keyPath.split(".");
let currentObj = a;
for (let i = 0; i < keys.length - 1; i++) {
currentObj = currentObj[keys[i]];
}
currentObj[keys[keys.length - 1]] = value;
return a;
}
key(a, keyPath, value);