-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathT3Q3.js
41 lines (27 loc) · 1.16 KB
/
T3Q3.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
/* Question 03 (stretch)
This is a STRETCH QUESTION.
Let's revisit Question 01 which had us convert an array of arrays into an object.
This time, make it support nested arrays.
The nested arrays also only contain 2 element arrays to represent key & value: [key, value]. However, this time we are allowing the value to be another array.
Non-array objects need NOT be supported/handled at all.
Examples:
- deepArrayToObject([['a', 1], ['b', 2], ['c', [['d', 4]]]])
=> { a: 1, b: 2, c: { d: 4 } }
- deepArrayToObject([['a', 1], ['b', 2], ['c', [['d', [['e', 5], ['f', 6]]]]]])
=> { a: 1, b: 2, c: { d: { e: 5, f: 6 } } }
*/
const deepArrayToObject = function (arr) {
const createdObject = {};
arr.forEach((element) => {
if(Array.isArray(element[1])) {
createdObject[element[0]] = deepArrayToObject(element[1]);
}
else {
createdObject[element[0]] = element[1];
}
});
return createdObject;
};
console.log(deepArrayToObject([['a', 1], ['b', 2], ['c', [['d', 4]]]]));
console.log("=============================")
console.log(deepArrayToObject([['a', 1], ['b', 2], ['c', [['d', [['e', 5], ['f', 6]]]]]]));