17

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'

Sunil Garg
  • 14,608
  • 25
  • 132
  • 189
FatalKeystroke
  • 2,882
  • 7
  • 23
  • 35
  • Key-value stores are objects in Javascript. Arrays are a special kind of object with numeric keys. Since you are talking about something with the key `'id'`, you're surely talking about an object rather than an array. – Chuck Sep 21 '12 at 00:06

6 Answers6

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

if (keys.length !== 1 || key !== "id" || text[key] !== "message")
    alert("Wrong object");
Bouke Versteegh
  • 4,097
  • 1
  • 39
  • 35
manager
  • 286
  • 1
  • 2
2

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?
  }
}
RobG
  • 142,382
  • 31
  • 172
  • 209
1
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');
timidboy
  • 1,702
  • 1
  • 16
  • 27
1

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

Barbara Jacob
  • 286
  • 4
  • 11
1

you can stringify it and try to match it with a regEx. Example:

if (JSON.stringify(test).match(/\"id":\"message\"/)) {
  console.log("bingo");
}
else  console.log("not found");
balafi
  • 2,143
  • 3
  • 17
  • 20
1
   const hasOnlyKey = (keyName: string, object: Object): boolean => {
        const objectKeys = Object.keys(object);

        return objectKeys.length === 1 && objectKeys[0] === keyName;
    }
Thabo
  • 1,303
  • 2
  • 19
  • 40