Searching For Existing Keys In Arrays And Objects In JavaScript

If you want to check if an object or array has a particular key you should first make sure that what you want to search for it in is an Object or an Array. You do this by checking the constructor of the thing you want to search. If it’s not an Object or Array then return false.

if (!search || (search.constructor !== Array && search.constructor !== Object)) {
	return false;
}

If it is either an Object or Array, then handling the two types is a matter of checking the key indexes for a match to handle searching Object keys, and if that doesn’t work, then you can return the key in array. If the key is not in the array it will be false upon being returned.

Here’s a function that will do this:

function keyExists(key, search) {
	if (!search || (search.constructor !== Array && search.constructor !== Object)) {
		return false;
	}
	for (var i = 0; i < search.length; i++) {
		if (search[i] === key) {
			return true;
		}
	}
	return key in search;
}

You pass it a key: the thing you’re searching for, and search: the object you want to search for it in.

Searching Arrays

keyExists('apple', ['apple', 'banana', 'orange']); // true
keyExists('fruit', ['apple', 'banana', 'orange']); // false

Searching Objects

keyExists('age', {'name': 'Jared', 'age': 29 }); // true
keyExists('title', {'name': 'Jared', 'age': 29 }); // false

You might wonder why you can’t just skip doing the loop and just return key in search. This won’t work when searching Objects because the in keyword is going to look for an index number not a string or Object key. You need to make sure that you first do the loop in case the object being searched is an Object, otherwise it’s an Array, if it makes it to that point at all after checking the constructor.

Leave a Reply

show allowed tags

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

By submitting a comment here you grant Anti-Code.com a perpetual license to reproduce your words and name/web site in attribution. Inappropriate comments will be removed at admin's discretion.