使用递归读取对象的属性和属性? [英] reading an object's attributes and properties using recursion?

查看:119
本文介绍了使用递归读取对象的属性和属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道我是否可以使用递归函数来读取对象的所有属性和属性,包括嵌套属性等。例如,如果我有一个对象,则为

I wonder if it would be possible for me to employ a recursive function to read all the attributes and properties of an object including the nested properties and such. for example, if I have an object:

  var mObj = {};
  mObj.countries = [];
  mObj.country = {};
  mObj.country.states = [];
  mObj.country.state = {};
  mObj.country.state = {};

我相信你能得到这张照片。如果它只是一个简单的对象,那么我可以使用for in循环,也许嵌套for in循环,一个对象有许多嵌套级别,然后使用嵌套的for in循环变得有些混乱。我认为使用递归会很棒。任何有助于此的帮助都会受到高度赞赏。

I am sure you get the picture. If it was just a simple object then I can employ "for in" loop, and perhaps nested "for in" loop, an object has numerous nested levels then using nested "for in" loops becomes somewhat chaos. I thought it would wonderful to employ recursion. Any help insight to this would highly appreciated.

谢谢。

推荐答案

这是一个快速示例,可以在您遇到任何问题时执行此操作。

Here's a quick example that does this in case you end up running into any problems.

var level = '';
var readProperties = function(val) {
    if (Object.prototype.toString.call(val) === '[object Object]') {
        for (var propertyName in val) {
            if (val.hasOwnProperty(propertyName)) {
                console.log(level + propertyName + ':');
                level += '  ';
                readProperties(val[propertyName]);
            }
        }
    }
    else {
        console.log(level + val);
        level = level.substring(0, level.length - 2);
    }
}

这篇关于使用递归读取对象的属性和属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆