admin管理员组文章数量:1173655
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'
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'
6 Answers
Reset to default 24var 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?
}
}
const hasOnlyKey = (keyName: string, object: Object): boolean => {
const objectKeys = Object.keys(object);
return objectKeys.length === 1 && objectKeys[0] === keyName;
}
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');
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...
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");
本文标签: How to determine if a Javascript object has only one specific keyvalue pairStack Overflow
版权声明:本文标题:How to determine if a Javascript object has only one specific key-value pair? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1737630069a1999562.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
'id'
, you're surely talking about an object rather than an array. – Chuck Commented Sep 21, 2012 at 0:06