猿问

大佬们遇到过这个问题吗?一道前端面试题

题目描述
有一个树形结构:
vardata={
key1:'str1',
key2:{
key3:'str3',
key4:'str4',
key5:{
key6:'str6'
},
key8:{
key9:'str9'
}
},
key7:"str7"
//...
}
实现一个方法getKeys(data,str),获取字符串str在data中所有的上级节点名称,例如:getKeys(data,'str1')返回'key1'getKeys(data,'str3')返回'key2key3'getKeys(data,'str6')返回'key2key5key6'
慕姐8265434
浏览 351回答 2
2回答

万千封印

functiongetKeys(data,str){varresult=[];functionrecursion(data,str){for(varkeyindata){if(data[key]==str){result.push(key);returnresult;}if(typeofdata[key]=='object'){result.push(key);returnrecursion(data[key],str)}}}recursion(data,str);returnresult.join('');}

HUH函数

varresult=[]constGetKey=(data,key)=>{for(letvindata){if(data[v]==key){result.push(v)returnresult}if(typeofdata[v]=='object'){result.push(v)returnGetKey(data[v],key)}}}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答