简体   繁体   中英

How to loop through object key values and nested values

I don't think "nested values" is the right term, but here's what I'm trying to do:

Let's say I have an object that looks like this:

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

And I want to check if either title or content.top or content.bottom contains a certain string.

I've found that I can loop through an object keys with something like this:

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

But what if the key is an object in itself and contains other keys? What if those keys are also objects with different keys? So basically, is there a way to search the entire object in a "deep" way, so that it searches all values no matter how deep the values are "nested"?

Nested objects form a recursive data structure called a tree, and a tree is easily browsable with recursive functions. Recursive functions are functions that call themselves, like the following browse function :

 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]"; } 

However, this function is designed to perform the same task over and over. A more generic approach would be to outsource operations applied to each leaf :

 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]"; } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM