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, chainList) {
let index;
var objList = [];
for (index in options) {
var obj = options[index];
if (chainList !== null) {
objList = chainList.slice()
}
objList.push(obj)
if (obj.id === findKey) {
return objList
} else if (obj.children && obj.children.length) {
return search(obj.children, findKey, objList)
}
}
}
console.log(search(options, "zhonghuamen", null))