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

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 know the property you want, wouldn't be quicker to just make a shallow copy of the object, pruned of everything is not needed?

var text = {
    id : "message",
    badProperty : "ugougo"
}

text = { id : text.id }

Assuming that I've understood correctly your question...


var moreThanOneProp = false;
for (var i in text) {
   if (i != 'id' || text[i] != 'message') {
      moreThanOneProp = true;
      break;
   }
}

if (!moreThanOneProp)
   alert('text has only one property');

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

if (keys.length !== 1 || key !== "id" || text[key] !== "message")
    alert("Wrong object");

Tags:

Javascript