首页 > 解决方案 > Javascript:递归问题 --> 返回深度嵌套对象中最长的键值

问题描述

下面是问题:

// 获取最长的名字

// 编写一个函数,getLongestName,它接受一个对象。该对象代表一个家谱。返回家族中最长的名字。

这是代码,但它返回错误:

let family = {
  'Beverly Marquez': {
    'Nina Rhone': {
      'William Rhodes': null,
      'Paul Nell': null,
      'Sir Paddington the Fourth, of the county Wilstonshire': null
    }
  }
};


function getLongestName (family){

  let longestName = ''; 

  for (let key in family){
    let value = family[key]
    console.log(value)

    if (typeof value === 'object'){
      let descendentLongestName = getLongestName (value)
    }

    else {
      descendentLongestName = value
    }

    if (descendentLongestName.length > longestName.length){
      let longestName = descendentLongestName
    }
  }
  return longestName; 
}


getLongestName(family); // => 'Sir Paddington the Fourth, of the county Wilstonshire'

当我运行上面的代码时,我收到以下错误:ReferenceError: descendentLongestName is not defined

我做错了什么?

标签: javascriptobjectrecursionnestedkey

解决方案


我不知道如何修复您的代码,但我想提出一个新的解决方案。

这个想法是将您的问题分解为两部分:

  • 递归地从嵌套对象中查找所有键
  • 从字符串数组中找到最长的一个

let longest = ary => ary
    .reduce((max, x) =>
        x.length > max.length ? x : max, '');

let allKeys = obj => obj
    ? Object.keys(obj).concat(
        ...Object.values(obj).map(allKeys))
    : [];

//

let family = {
    'Beverly Marquez': {
        'Nina Rhone': {
            'William Rhodes': null,
            'Paul Nell': null,
            'Sir Paddington the Fourth, of the county Wilstonshire': null,
        }
    }
};

console.log(longest(allKeys(family)));


推荐阅读