I want to write a code in javascript to convert a nested array in to a nested object. The point is every single elements in the nested array would be an array itself, so should convert to a nested object:
Examples:
- [['a', 1], ['b', 2], ['c', [['d', 4]]]] => { a: 1, b: 2, c: { d: 4 } }
- [['a', 1], ['b', 2], ['c', [['d', [['e', 5], ['f', 6]]]]]] => { a: 1, b: 2, c: { d: { e: 5, f: 6 } } }
I tried to go with this concept: define a function to iterate over the base array. for every single element, it will make a key:value for the object. if the value is an array, the function will call itself. but Actually I dont know how to write it.
const nestedArrayToObject = function (arr) {
let obj = {};
for (let i = 0; i < arr.length; i++) {
let key = arr[i][0];
let val = arr[i][1];
if (!Array.isArray(val)) {
obj[key] = val;
} else {
nestedArrayToObject(val); ???
}
}
return obj;
};