What is the best and fastest way in JS to validate if an object exists and if it does then a certain property exists on it as well?

时间:2017-08-29 14:28:26

标签: javascript json

I have to put a validity check before performing any operation using the object which -

  1. If that object exists.
  2. If its exists then a certain property also exists on it.

For ex-

var obj = {
    key: "value"
}

Now the most conventional way to do this is-

if(obj) {
    if(obj.hasOwnProperty('key') {
        //Do some action (validity check pass)
        //For Example- console.log(obj.key);
    }
}

But i am looking for a more faster and efficient way there must be to solve this.

4 个答案:

答案 0 :(得分:1)

我做:

if ( typeof obj != "undefined" && obj.hasOwnProperty('key') ) 
{ 
    console.log('found'); 
} 
else 
{ 
    console.log('not found');
}

答案 1 :(得分:1)

喜欢这个吗?

var obj = {
    key: "value"
}
var objx = null;


if(obj && "key" in obj){
	document.getElementById("check_one").innerHTML = "is valid";
}else{
	document.getElementById("check_one").innerHTML ="is not valid";
}
if(obj && "notkey" in obj){
	document.getElementById("check_two").innerHTML = "is valid";
}else{
	document.getElementById("check_two").innerHTML ="is not valid";
}

if(objx && "key" in objx){
	document.getElementById("check_three").innerHTML = "is valid";
}else{
	document.getElementById("check_three").innerHTML ="is not valid";
}
<p>
Check One (should be valid): <span id="check_one"></span>
</p>
<p>
Check Two (should be invalid): <span id="check_two"></span>
</p>
<p>
Check Three (should be invalid) <span id="check_three"></span>
</p>

根据您所需的浏览器支持,您也可以使用Reflect.has

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/has

Reflect.has(obj, 'key');

如果你想支持旧IE,我想你必须使用HasOwnProperty,那里不会有任何其他可能性 - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

答案 2 :(得分:1)

你绝对可以将这两个陈述合并为一个@Stuart和@phuzi:

if(!!obj && obj.hasOwnProperty('key')

同样hasOwnProperty将忽略通过原型的所有继承属性。如果您希望包含继承的属性,则可以在此处使用in运算符。

if (!!ob && (prop in ob))

答案 3 :(得分:0)

如果你关心原型链,那么没有更好的方法;你必须检查链中的每个链接。

如果没有,并且属性通常存在,则可能值得访问该属性并捕获任何异常,但使用性能测试来查看。

但我要说的问题是你对输入的限制不够:要求代码的调用者提供一个对象并让他们处理它。

对我而言,它“闻起来”就像两个独立的问题:“对象是否存在?”,如果是这样,提供默认值和“对象是否具有此属性?”,业务逻辑。

如果是,请使用标准模式设置默认值:“obj = obj || {};”例如;然后测试成为一个单独的调用,很难“更快”。