How to Check If an Object Has a Key in JavaScript

How do I check if an object has a key in JavaScript?

Try the JavaScript in operator.

if ('key' in myObj)

And the inverse.

if (!('key' in myObj))

Be careful! The in operator matches all object keys, including those in the object's prototype chain.

Use myObj.hasOwnProperty('key') to check an object's own keys and will only return true if key is available on myObj directly:

myObj.hasOwnProperty('key')

Unless you have a specific reason to use the in operator, using myObj.hasOwnProperty('key') produces the result most code is looking for.

How do I check if an object has a specific property in JavaScript?

2022 UPDATE

Object.hasOwn()

Object.hasOwn() is recommended over Object.hasOwnProperty() because it works for objects created using Object.create(null) and with objects that have overridden the inherited hasOwnProperty() method. While it is possible to workaround these problems by calling Object.prototype.hasOwnProperty() on an external object, Object.hasOwn() is more intuitive.

Example

const object1 = {
prop: 'exists'
};

console.log(Object.hasOwn(object1, 'prop'));
// expected output: true


Original answer

I'm really confused by the answers that have been given - most of them are just outright incorrect. Of course you can have object properties that have undefined, null, or false values. So simply reducing the property check to typeof this[property] or, even worse, x.key will give you completely misleading results.

It depends on what you're looking for. If you want to know if an object physically contains a property (and it is not coming from somewhere up on the prototype chain) then object.hasOwnProperty is the way to go. All modern browsers support it. (It was missing in older versions of Safari - 2.0.1 and older - but those versions of the browser are rarely used any more.)

If what you're looking for is if an object has a property on it that is iterable (when you iterate over the properties of the object, it will appear) then doing: prop in object will give you your desired effect.

Since using hasOwnProperty is probably what you want, and considering that you may want a fallback method, I present to you the following solution:

var obj = {
a: undefined,
b: null,
c: false
};

// a, b, c all found
for ( var prop in obj ) {
document.writeln( "Object1: " + prop );
}

function Class(){
this.a = undefined;
this.b = null;
this.c = false;
}

Class.prototype = {
a: undefined,
b: true,
c: true,
d: true,
e: true
};

var obj2 = new Class();

// a, b, c, d, e found
for ( var prop in obj2 ) {
document.writeln( "Object2: " + prop );
}

function hasOwnProperty(obj, prop) {
var proto = obj.__proto__ || obj.constructor.prototype;
return (prop in obj) &&
(!(prop in proto) || proto[prop] !== obj[prop]);
}

if ( Object.prototype.hasOwnProperty ) {
var hasOwnProperty = function(obj, prop) {
return obj.hasOwnProperty(prop);
}
}

// a, b, c found in modern browsers
// b, c found in Safari 2.0.1 and older
for ( var prop in obj2 ) {
if ( hasOwnProperty(obj2, prop) ) {
document.writeln( "Object2 w/ hasOwn: " + prop );
}
}

The above is a working, cross-browser, solution to hasOwnProperty(), with one caveat: It is unable to distinguish between cases where an identical property is on the prototype and on the instance - it just assumes that it's coming from the prototype. You could shift it to be more lenient or strict, based upon your situation, but at the very least this should be more helpful.

Checking if a key exists in a JavaScript object?

Checking for undefined-ness is not an accurate way of testing whether a key exists. What if the key exists but the value is actually undefined?

var obj = { key: undefined };
console.log(obj["key"] !== undefined); // false, but the key exists!

check if object has key in Typescript and use that key

You can create a type guard:

function isValidParam(k: string): k is keyof typeof show {
return k in show;
}

const showDialog = $page.query.get('show') || '';

if (isValidParam(showDialog)) {
show[showDialog] = true;
}

but you decide if it's worth it. I'd probably just keep the cast, personally.

How to check if object has any properties in JavaScript?

You can loop over the properties of your object as follows:

for(var prop in ad) {
if (ad.hasOwnProperty(prop)) {
// handle prop as required
}
}

It is important to use the hasOwnProperty() method, to determine whether the object has the specified property as a direct property, and not inherited from the object's prototype chain.

Edit

From the comments: You can put that code in a function, and make it return false as soon as it reaches the part where there is the comment

Check if Object has keys

I resolve my question with:

   function check(objs) {
for (let obj of objs) {
if(!('name' in obj) &&
!('value' in obj))
throw new Error('invalid')
if('name' in obj)
check(obj.items)
}
}

How to check if an object has a specific key without try/catch

Reading an undefined key safely produces undefined, but reading a key from undefined will throw, so the problem will be specifically that data[0] doesn't exist, not that data[0]["read.nores"] doesn't exist.

To check for that, change it to:

if (data[0] && data[0]["read.nores"]) {
return;
}

How to check if an object key is in another object of objects

  • Convert the allMembers object into an array of key value pairs using Object.entries.

  • Filter the items that have value true using Array.prototype.filter.

  • Transform the array back to an object using Object.fromEntries.

const 
allMembers = {'-Lz8YxHiwp8QZW3TqAFn': {first: 'foo',last: 'bar',uid: '-Lz8YxHiwp8QZW3TqAFn'},'-Lz8YxHqQXWoaGOFRLrO': {first: 'foo',last: 'bar',uid: '-Lz8YxHqQXWoaGOFRLrO'},'-Lz8YxHsMItaaTVNyQRE': {first: 'foo',last: 'bar',uid: '-Lz8YxHsMItaaTVNyQRE'},'-Lz8YxHwuVBMWl0Go6C5': {first: 'foo',last: 'bar',uid: '-Lz8YxHwuVBMWl0Go6C5'},'-Lz8YxHy0S-QkDaE1PkX': {first: 'foo',last: 'bar',uid: '-Lz8YxHy0S-QkDaE1PkX'}},
attendanceData = {'-Lz8YxHiwp8QZW3TqAFn': true,'-Lz8YxHqQXWoaGOFRLrO': true,'-Lz8YxHsMItaaTVNyQRE': true,'-Lz8YxHwuVBMWl0Go6C5': false,'-Lz8YxHy0S-QkDaE1PkX': true,'-Lz8YxIFA1XGVmaNfNr3': false,'-Lz8YxIJVZnIIj7RgEzg': false},
filteredMembers = Object.fromEntries(
Object.entries(allMembers).filter(([k]) => attendanceData[k])
);

console.log(filteredMembers);


Related Topics



Leave a reply



Submit