<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
var arr = [{
key: '1',
children: [
{
key: '1-0',
children: [
{ key: '1-0-0' }
]
}
]
},
{
key: '2',
children: [
{
key: '2-0',
children: [
{
key: '2-0-0',
children: [
{ key: '2-0-0-0' }
]
}
]
},
{
key: '2-1',
children: [
{ key: '2-1-0' }
]
}
]
}]
const getParentId = (treeData, id) => {
let pid = '';
const fn = (treeData, key) => {
for (let i = 0; i < treeData.length; i++) {
const item = treeData[i]
if (item.key === id) {
pid = key
return;
}
if (item?.children) fn(item.children, item.key);
}
};
fn(treeData, id);
return pid;
};
console.log('father of 2-0-0-0 is:', getParentId(arr, '2-0-0-0'));
</script>
</body>
</html>