Sunday, 27 November 2016

How to check if a key exists in an object in javascript





I have the following object literal:



{ 
'key1':
{
id: 'rr323',

d: undefined,
x: 560,
y: 150
},
'key2':
{
id: 'rr231',
d: undefined,
x: 860,
y: 90

}
}


I want to implement an if statement such as below:



if(key DOES NOT exist in object){  
//perform certain function
}



I tried the following:



var key = key1;
if(!(key in global_move_obj)){
// function
}


But that always returns true value when it should return false.



Answer



Use the hasOwnProperty call



if (!obj.hasOwnProperty(key)) {

}


https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...