简体   繁体   English

使用递归返回嵌套的 object - Javascript

[英]Return nested object with recursion - Javascript

I have an object with nested object:我有一个带有嵌套 object 的 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.我需要返回所有key: value list的值,我必须使用递归。 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.我试图将嵌套的 object 推送到 function 中的局部变量,但由于名称不同,它在第二次迭代中失败。

Here is the function:这是 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.它应该返回value属性。 In this case在这种情况下

1
2
3
4

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

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:您可以创建一个 function 来检查是否为给定的 object 定义了next一个,如果是,您可以将该value与 rest 的进一步递归调用一起添加到数组中:

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

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)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM