要遍歷嵌套JavaScript 物件並定位具有特定標籤的對象,請依照下列步驟操作:
遞歸地迭代巢狀物件:
const iterate = (obj) => { Object.keys(obj).forEach(key => { console.log(`key: ${key}, value: ${obj[key]}`) if (typeof obj[key] === 'object' && obj[key] !== null) { iterate(obj[key]) } }) } iterate(obj); // obj is the main object to be traversed
對於非遞迴方法:
const iterate = (obj) => { const stack = [obj]; while (stack?.length > 0) { const currentObj = stack.pop(); Object.keys(currentObj).forEach(key => { console.log(`key: ${key}, value: ${currentObj[key]}`); if (typeof currentObj[key] === 'object' && currentObj[key] !== null) { stack.push(currentObj[key]); } }); } };
考慮以下嵌套物件:
var cars = { label: 'Autos', subs: [ { label: 'SUVs', subs: [] }, { label: 'Trucks', subs: [ { label: '2 Wheel Drive', subs: [] }, { label: '4 Wheel Drive', subs: [ { label: 'Ford', subs: [] }, { label: 'Chevrolet', subs: [] } ] } ] }, { label: 'Sedan', subs: [] } ] };
擷取帶有標籤" 的物件4 Wheel Drive 」使用遞歸方法,呼叫:
iterate(cars);
要使用非遞歸方法檢索相同的對象,呼叫:
iterate(cars);
這將記錄所有密鑰-嵌套對像中的值對,包括所需的對象。
以上是如何透過標籤尋找嵌套 JavaScript 物件中的特定物件?的詳細內容。更多資訊請關注PHP中文網其他相關文章!