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'
Example 2: Check if Key Exists in Object Using hasOwnProperty() The key exists. In the above program, the hasOwnProperty() method is used to check if a key exists in an object. The hasOwnProperty() method returns true if the specified key is in the object, otherwise it returns false .
You can use Object. values(): The Object. values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
The hasOwnProperty() method will check if an object contains a direct property and will return true or false if it exists or not. The hasOwnProperty() method will only return true for direct properties and not inherited properties from the prototype chain.
prototype. hasOwnProperty() The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).
var keys = Object.keys(text);
var key = keys[0];
if (keys.length !== 1 || key !== "id" || text[key] !== "message")
alert("Wrong object");
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?
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With