简体   繁体   English

如何遍历对象键值和嵌套值

[英]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. 我想检查title或content.top或content.bottom是否包含某个字符串。

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 : 递归函数是可以自行调用的函数,例如以下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]"; } 

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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