How to read an object's properties while using a recursive function in Javascript?

后端 未结 1 1987
不思量自难忘°
不思量自难忘° 2021-01-15 12:37

I wonder if someone can point me into the right direction on this. When I have an object, I usually read its properties via FOR IN LOOP. And since I know what the properties

相关标签:
1条回答
  • 2021-01-15 13:24

    Here's a basic example:

    var mObj = {};
    mObj.mArr = [];
    mObj.mArr.push({id:['id1','id2','id3']});
    mObj.mArr.push({days:['Monday','Tuesday','Wednesday','Thursday']});
    mObj.mArr.push({colors:['orange','red','blue','green','yellow','white']});
    
    function r(obj) {
        if (obj)
            for (var key in obj) {
                if (typeof obj[key] == "object")
                    r(obj[key]);
                else if (typeof obj[key] != "function")
                    console.log(obj[key])
            }
    
        return;
    } 
    
    r(mObj);
    

    if there is an object not a function call the function again, else console log the value if it is not a function.

    0 讨论(0)
提交回复
热议问题