3 回答
![?](http://img1.sycdn.imooc.com/5333a2320001acdd02000200-100-100.jpg)
TA贡献1818条经验 获得超3个赞
你忘记return了功能
let obj = {
"uuid": "344444",
"entityName": "priceFormationPhase",
"id": 2,
"value": "foo",
"children": {
"4": {
"uuid": "44444",
"entityName": "organization",
"id": 4,
"value": "ffffff",
"children": {
"344534": {
"uuid": "33333",
"entityName": "contract",
"id": 928688,
"value": "dh",
"children": {
"345345": {
"uuid": "222222222",
"entityName": "contractPhase",
"id": 234324234,
"value": "111",
"children": {}
}
}
}
}
}
}
};
function findContractStage(obj) {
if ((typeof obj.children === 'object') && (Object.keys(obj.children).length > 0)) {
return findContractStage(obj.children);
} else if (typeof obj[Object.keys(obj)[0]] === 'object') {
return findContractStage(obj[Object.keys(obj)[0]]);
} else if (obj.entityName) {
console.log(`final result: ${obj.id}`);
return obj.id;
}
}
let contractStageId = findContractStage(obj);
console.log(`contractStageId: ${contractStageId}`);
![?](http://img1.sycdn.imooc.com/533e4c5600017c5b02010200-100-100.jpg)
TA贡献1719条经验 获得超6个赞
您不会返回递归时获得的值。尝试这个:
let obj = {
"uuid": "344444",
"entityName": "priceFormationPhase",
"id": 2,
"value": "foo",
"children": {
"4": {
"uuid": "44444",
"entityName": "organization",
"id": 4,
"value": "ffffff",
"children": {
"344534": {
"uuid": "33333",
"entityName": "contract",
"id": 928688,
"value": "dh",
"children": {
"345345": {
"uuid": "222222222",
"entityName": "contractPhase",
"id": 234324234,
"value": "111",
"children": {}
}
}
}
}
}
}
};
function findContractStage(obj) {
if ((typeof obj.children === 'object') && (Object.keys(obj.children).length > 0)) {
return findContractStage(obj.children);
} else if (typeof obj[Object.keys(obj)[0]] === 'object') {
return findContractStage(obj[Object.keys(obj)[0]]);
} else if (obj.entityName) {
console.log(`final result: ${obj.id}`);
return obj.id;
}
}
let contractStageId = findContractStage(obj);
console.log(`contractStageId: ${contractStageId}`);
![?](http://img1.sycdn.imooc.com/53339fdf00019de902200220-100-100.jpg)
TA贡献1853条经验 获得超9个赞
您需要在递归调用之前添加“返回”
return findContractStage(obj.children);
和
return findContractStage(obj[Object.keys(obj)[0]]);
因此,您的递归函数会尽可能深入并返回您的 id 值。
添加回答
举报