Skip to content
Advertisement

How to check if key exists in array of object

I am trying to find out if the given key exists in array of object. if the value key exists then i want to return true else false.

i giving input of key from text box and then checking if the key exists in array of objects, but i couldn’t get it.

here is what i have tried

code:

var obj = [{
    "7364234":"hsjd",
    "tom and jerry":"dsjdas",
    "mickey mouse":"kfjskdsad",
    "popeye the sailor man":"alkdsajd",
    "the carribean":"kasjdsjad"
}]

var val = $("input[name='type_ahead_input']").val();

if (obj[val]) {
    console.log('exists');
} else {
    console.log('does not exist');
}

if i give input as ‘the carribean‘ which exists in array of object, even then its outputting in console as does not exist.

how can i resolve this?

Advertisement

Answer

you can use typeof to check if key exist

if (typeof obj[0][val] !== "undefined" ) {
    console.log('exists');
} else {
    console.log('does not exist');
}

Note: There is index 0 coz the object that you are checking is an element 0 of the array obj


Here is a fiddle:

var obj = [{
		"7364234":"hsjd",
		"tom and jerry":"dsjdas",
		"mickey mouse":"kfjskdsad",
		"popeye the sailor man":"alkdsajd",
		"the carribean":"kasjdsjad"
	}];

	if ( typeof obj[0]["the carribean"] !== 'undefined' ) {
		console.log('exists');
	} else {
		console.log('does not exist');
	}

As suggested by Cristy below, you can also use obj[0][val] === undefined

You can also:

var obj = [{
    "7364234":"hsjd",
    "tom and jerry":"dsjdas",
    "mickey mouse":"kfjskdsad",
    "popeye the sailor man":"alkdsajd",
    "the carribean":"kasjdsjad"
}];

var val = "7364234";

if ( val in obj[0] ) {
    console.log('exists');
} else {
    console.log('does not exist');
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement