4

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
2
  • Well where in the recursive function are you actually printing anything to the output? Commented Sep 26, 2019 at 10:58
  • 1
    You should not check whether the object has a .next property, you should check whether nested is null. Commented Sep 26, 2019 at 10:59

4 Answers 4

7

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));

Sign up to request clarification or add additional context in comments.

1 Comment

Here is another one for you stackoverflow.com/questions/71395515/…
3

You can create a function which checks to see if next is defined for a given object, if it is, you can add the value into an array, along with the rest of the values retrieved from further recursive calls:

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

const get_keys = ({value, next}) => 
	next ? [value, ...get_keys(next)] : [value];
  
console.log(get_keys(list));

Comments

2

Here's a method that attempts to stay close to your own attempt.

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

function printList(list){
  if (!list)
    return;

  console.log(list.value)

  if (list.hasOwnProperty('next'))
    printList(list.next);
}

printList(list)

1 Comment

I already find the answer and I like it. But anyway your answer works and it at least deserves an upvote. Thank You very much for your time and effort!
0
var sum = 0;
function printList(list) {
  if (list.next) {
    sum = sum + list.value;
    printList(list.next);
  }
  if (!list.next) {
    sum = sum + list.value;
  }
  return sum;
}
console.log(printList(list));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.