JSFiddle - React, Tailwind, and code Playground
by ruirui
JavaScript
const options = [{
id: 'zhejiang',
text: 'Zhejiang',
children: [{
id: 'hangzhou',
text: 'Hangzhou',
children: [{
id: 'xihu',
text: 'West Lake'
}]
}]
}, {
id: 'jiangsu',
text: 'Jiangsu',
children: [{
id: 'nanjing',
text: 'Nanjing',
children: [{
id: 'zhonghuamen',
text: 'Zhong Hua Men'
}]
}]
}];
function search(options, findKey) {
var chain = null;
return recurision(options, findKey);
function recurision(options, findKey) {
if (!options)
return null
for (var i = 0; i < options.length; i++) {
if (options[i].id == findKey) {
chain = []
chain.push(options[i])
break;
}
if (options[i].children) {
recurision(options[i].children, findKey)
if (chain !== null) {
chain.push(options[i])
}
}
}
return chain;
}
}
console.log(search(options, "zhonghuamen"))