What would be the easiest way to determine if a Javascript object has only one specific key-value pair?
For example, I need to make sure that the object stored in the variable text only contains the key-value pair 'id' : 'message'
If you are talking about all enumerable properties (i.e. those on the object and its [[Prototype]] chain), you can do:
for (var prop in obj) {
if (!(prop == 'id' && obj[prop] == 'message')) {
// do what?
}
}
If you only want to test enumerable properties on the object itself, then:
for (var prop in obj) {
if (obj.hasOwnProperty(prop) && !(prop == 'id' && obj[prop] == 'message')) {
// do what?
}
}
'id', you're surely talking about an object rather than an array.