I have an array of JSON objects imdb
and I want to check if a key exists. I have tried couple different methods but none of them shows the correct result. I looked into this post but doesn't help. Below code
var imdb = [{"123":"hi"}, {"234":"hello"}]; //array of JSON object
var valEventTime = 123; //key I want to find if exists
//approach 1
function getValueByKey(key, data) {
var i, len = data.length;
for (i = 0; i < len; i++) {
if (data[i] && data[i].hasOwnProperty(key)) {
return data[i][key];
}
}
return -1;
}
if(getValueByKey(valEventTime, imdb) > -1){
console.log("Yes");
}
else {
console.log("NOT")
}
//approach 2
if (imdb[valEventTime]) {
console.log("Yes");
} else {
console.log("NOT")
}
//approach 3
var keys=Object.keys(imdb)
for(var i=0;i<keys.length;i++){
if(keys[i]==valEventTime)
{//check your key here
console.log("Yes")
}
else console.log("NOT")
}
The output always shows NOT
even though I am searching for a key that already exists (123
). Please suggest.