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