I have an object with nested object:
JavaScript
x
14
14
1
let list = {
2
value: 1,
3
next: {
4
value: 2,
5
next: {
6
value: 3,
7
next: {
8
value: 4,
9
next: null
10
}
11
}
12
}
13
};
14
I need to return all key: value
of list
and I must use recursion. I have tried to push the nested object to the local variable in the function, but it fails in the second iteration because the names are different.
Here is the function:
JavaScript
1
11
11
1
function printList(list){
2
let nested = {};
3
4
if(list.hasOwnProperty('next')) {
5
nested = list.next;
6
printList(nested);
7
} else {
8
return nested;
9
}
10
}
11
Is there a way to solve it with recursion?
It should return the value
properties. In this case
JavaScript
1
5
1
1
2
2
3
3
4
4
5
Advertisement
Answer
You could return an array with the values and get the nested values after a check
JavaScript
1
7
1
function printList({ value, next }) {
2
return [value, (next ? printList(next) : [])]
3
}
4
5
let list = { value: 1, next: { value: 2, next: { value: 3, next: { value: 4, next: null } } } };
6
7
console.log(printList(list));