Printing object's keys and values

后端 未结 7 1020
暗喜
暗喜 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:52

    Lets say that we have a mode object that has some strings in it for example. If we were to do MODE.toString() with just alpha, beta, gamma in the object, what will be returned is [object Object] which is not useful.

    Instead, lets say we wanted to get something nice back like Normal, Sepia, Psychedelic. To do that, we could add a toString: function(){...} to our object that will do just that. One catch to this however is that if we loop through everything in the object, the function it self will also be printed, so we need to check for that. In the example I'll check toString specifically, however, other checks like ... && typeof MODE[key] == "string" could be used instead

    Following is some example code, calling MODE.toString(); will return Normal, Sepia, Psychedelic

    var MODE = {alpha:"Normal", beta:"Sepia", gamma:"Psychedelic",
        toString: function() {
            var r = "";
            for (var key in MODE) {
                if (MODE.hasOwnProperty(key) && key != "toString") {
                    r+= r !== "" ? ", ":"";
                    r+= MODE[key];
                }
            }
            return r;
        }
    };
    

提交回复
热议问题