Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a Javascript object has only one specific key-value pair?

Tags:

javascript

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'

like image 255
FatalKeystroke Avatar asked Sep 21 '12 00:09

FatalKeystroke


People also ask

How do you check if a key-value pair exists in a JavaScript object?

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 .

How do you check if an object has a specific value in JavaScript?

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).

How do you know if an object has one property?

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.

How do you check if an object has a specific property in JavaScript?

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).


2 Answers

var keys = Object.keys(text);
var key = keys[0];

if (keys.length !== 1 || key !== "id" || text[key] !== "message")
    alert("Wrong object");
like image 182
manager Avatar answered Nov 04 '22 18:11

manager


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?
  }
}
like image 2
RobG Avatar answered Nov 04 '22 18:11

RobG