javascript - 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
我做错了什么?
解决方案
我不知道如何修复您的代码,但我想提出一个新的解决方案。
这个想法是将您的问题分解为两部分:
- 递归地从嵌套对象中查找所有键
- 从字符串数组中找到最长的一个
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)));
推荐阅读
- node.js - 无法在 heroku 上托管 node.js 应用程序。正在显示应用程序错误
- css - CSS 网格在 Internet Explorer 中不起作用
- java - 对象相等性 vs 唯一性
- c# - C# Razor 在成功刷新错误时提交表单
- visual-studio-code - 用于 VS Code 的 Vim EasyMotion 未激活
- haskell - 在这种特殊情况下,为什么我会收到不在范围内的错误变量?
- intellij-idea - LibGDX 所有库在 IDE 重新启动后被删除
- python - 如何处理“无法将字符串转换为浮点数”错误
- java - 动态读取 hashmap 嵌套属性
- spring - 为什么方法看不到构造函数中设置的值?(弹簧靴)