Printing object's keys and values

后端 未结 7 1022
暗喜
暗喜 2021-02-01 06:04

I want to print a key: value pair from javascript object. I can have different keys in my array so cannot hardcode it to object[0].key1

var filters = [{\"user\"         


        
7条回答
  •  一整个雨季
    2021-02-01 06:44

    If you want to print key and value, even for nested object then you can try this function:

    function printObjectData(obj, n = 0){
        let i = 0;
        var properties = Object.keys(obj);
    
        let tab = "";
        for(i = 0; i < n; i++)
            tab += "\t";
    
        for(i = 0; i < properties.length; i++){                  
            if(typeof(obj[properties[i]]) == "object"){
                console.log(tab + properties[i] + ":");
                printObjectData(obj[properties[i]], n + 1);
            }
            else
                console.log(tab + properties[i] + " : " + obj[properties[i]]);                    
        }
    }
    
    printObjectData(filters);
    

    and the solution will look like this:

    0:
        user : abc 
    1:
        application : xyz 
    

    and if you want to remove 0: and 1: then simply remove

    console.log(tab + properties[i] + ":"); 
    

    after the if statement

提交回复
热议问题