I am writing a function to convert array to List using Javascript.
If the input array is as below:
let inputArray = [1,2,3]
The output object should be like the below:
let outputList = {
value: 1,
rest: {
value: 2,
rest: {
value : 3,
rest: null } } }
I have the below function that accepts a nested object as its parameter and returns a string that represents where in the object, the property is null:
function getLastValue(object) {
let s = '';
if (object.rest) {
return s += '[rest]' + getLastValue(object.rest);
} else {
return s;
}
And the below function that converts an array to a list:
var list = {value: '', rest: null};
function constructList(arr) {
for (let prop of arr) {
let lastValue = getLastValue(list);
`${list}${lastValue}`.value = prop;
`${list}${lastValue}`.rest = null;
}
return list;
}
The constructList function fails to work as ${list}${lastValue}
is a string. I need to convert the above from
'list[rest][rest]'
to
list[rest][rest]
Any help is appreciated!