簡體   English   中英

如何遍歷對象鍵值和嵌套值

[英]How to loop through object key values and nested values

我不認為“嵌套的值”是正確的術語,但是我正在嘗試這樣做:

假設我有一個看起來像這樣的對象:

{
    title: 'Foo',
    content: {
        top: 'Bar',
        bottom: 'Baz'
    }
}

我想檢查title或content.top或content.bottom是否包含某個字符串。

我發現我可以像這樣遍歷對象鍵:

for (var property in object) {
    if (object.hasOwnProperty(property)) {
        // do stuff
    }
}

但是,如果鍵本身是對象並且包含其他鍵,該怎么辦? 如果這些鍵也是具有不同鍵的對象怎么辦? 因此,從根本上講,有沒有一種方法可以以“深度”方式搜索整個對象,以便無論“嵌套”值有多深都可以搜索所有值?

嵌套對象形成稱為樹的遞歸數據結構,並且使用遞歸功能可輕松瀏覽樹。 遞歸函數是可以自行調用的函數,例如以下browse函數:

 var tree = { a: "azerty", child: { q: "qwerty" } }; browse(tree); function browse (tree) { for (var k in tree) { if (isTree(tree[k])) { browse(tree[k]); } else { console.log(k, tree[k]); } } } function isTree (x) { return Object.prototype.toString.call(x) === "[object Object]"; } 

但是,此功能旨在反復執行相同的任務。 一種更通用的方法是將應用於每個葉子的操作外包:

 var tree = { a: 'azerty', child: { q: 'qwerty' } }; browse(tree, log); browse(tree, searchQ); function browse (tree, operation) { for (var k in tree) { if (isTree(tree[k])) { browse(tree[k], operation); } else { operation(k, tree[k]); } } } function log (label, leaf) { console.log("logged", label, leaf); } function searchQ (label, leaf) { if (leaf.indexOf('q') !== -1) { console.log("found", label, leaf); } } function isTree (x) { return Object.prototype.toString.call(x) === "[object Object]"; } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM