3 回答

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超3個(gè)贊
你忘記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}`);

TA貢獻(xiàn)1719條經(jīng)驗(yàn) 獲得超6個(gè)贊
您不會(huì)返回遞歸時(shí)獲得的值。嘗試這個(gè):
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}`);

TA貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超9個(gè)贊
您需要在遞歸調(diào)用之前添加“返回”
return findContractStage(obj.children);
和
return findContractStage(obj[Object.keys(obj)[0]]);
因此,您的遞歸函數(shù)會(huì)盡可能深入并返回您的 id 值。
添加回答
舉報(bào)