Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return nested object with recursion - Javascript

I have an object with nested object:

let list = {
  value: 1,
  next: {
    value: 2,
    next: {
      value: 3,
      next: {
        value: 4,
        next: null
      }
    }
  }
};

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:

function printList(list){
  let nested = {};

  if(list.hasOwnProperty('next')) {
      nested = list.next;
      printList(nested);
  } else {
    return nested;
  }
}

Is there a way to solve it with recursion?

It should return the value properties. In this case

1
2
3
4
like image 740
Robert Hovhannisyan Avatar asked Sep 13 '25 17:09

Robert Hovhannisyan


1 Answers

You could return an array with the values and get the nested values after a check

function printList({ value, next }) {
    return [value, ...(next ? printList(next) : [])]
}

let list = { value: 1, next: { value: 2, next: { value: 3, next: { value: 4, next: null } } } };

console.log(printList(list));
like image 100
Nina Scholz Avatar answered Sep 16 '25 08:09

Nina Scholz