[javascript] Checking if a key exists in a JavaScript object?

Here's a helper function I find quite useful

This keyExists(key, search) can be used to easily lookup a key within objects or arrays!

Just pass it the key you want to find, and search obj (the object or array) you want to find it in.

_x000D_
_x000D_
function keyExists(key, search) {_x000D_
        if (!search || (search.constructor !== Array && search.constructor !== Object)) {_x000D_
            return false;_x000D_
        }_x000D_
        for (var i = 0; i < search.length; i++) {_x000D_
            if (search[i] === key) {_x000D_
                return true;_x000D_
            }_x000D_
        }_x000D_
        return key in search;_x000D_
    }_x000D_
_x000D_
// How to use it:_x000D_
// Searching for keys in Arrays_x000D_
console.log(keyExists('apple', ['apple', 'banana', 'orange'])); // true_x000D_
console.log(keyExists('fruit', ['apple', 'banana', 'orange'])); // false_x000D_
_x000D_
// Searching for keys in Objects_x000D_
console.log(keyExists('age', {'name': 'Bill', 'age': 29 })); // true_x000D_
console.log(keyExists('title', {'name': 'Jason', 'age': 29 })); // false
_x000D_
_x000D_
_x000D_

It's been pretty reliable and works well cross-browser.

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to object

How to update an "array of objects" with Firestore? how to remove json object key and value.? Cast object to interface in TypeScript Angular 4 default radio button checked by default How to use Object.values with typescript? How to map an array of objects in React How to group an array of objects by key push object into array Add property to an array of objects access key and value of object using *ngFor