确定 Javascript 对象是否只有一个特定的键值对的最简单方法是什么?
例如,我需要确保存储在变量中的对象text只包含键值对'id' : 'message'
var keys = Object.keys(text);
var key = keys[0];
if (keys.length !== 1 || key !== "id" || text[key] !== "message")
    alert("Wrong object");
    如果您正在谈论所有可枚举的属性(即对象及其[[Prototype]]链上的属性),您可以这样做:
for (var prop in obj) {
  if (!(prop == 'id' && obj[prop] == 'message')) {
    // do what?
  }
}
如果您只想测试对象本身的可枚举属性,那么:
for (var prop in obj) {
  if (obj.hasOwnProperty(prop) && !(prop == 'id' && obj[prop] == 'message')) {
    // do what?
  }
}
    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 text = {
    id : "message",
    badProperty : "ugougo"
}
text = { id : text.id }
假设我已经正确理解了你的问题......
您可以对其进行字符串化并尝试将其与正则表达式匹配。例子:
if (JSON.stringify(test).match(/\"id":\"message\"/)) {
  console.log("bingo");
}
else  console.log("not found");