In Javascript. how can I tell if a field exists inside an object?

Javascript

Javascript Problem Overview


And of course I want to do this code-wise. It's not that there isn't alternative to this problem I'm facing, just curious.

Javascript Solutions


Solution 1 - Javascript

This will ignore attributes passed down through the prototype chain.

if(obj.hasOwnProperty('field'))
{
    // Do something
}

Solution 2 - Javascript

UPDATE: use the hasOwnProperty method as Gary Chambers suggests. The solution below will work, but it's considered best practice to use hasOwnProperty.

if ('field' in obj) {
}

Solution 3 - Javascript

In addition to the above, you can use following way:

if(obj.myProperty !== undefined) {
}

Solution 4 - Javascript

There is has method in lodash library for this. It can even check for nested fields.

_.has(object, 'a');     
_.has(object, 'a.b');

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKhoiView Question on Stackoverflow
Solution 1 - JavascriptGary ChambersView Answer on Stackoverflow
Solution 2 - JavascriptPeter KruithofView Answer on Stackoverflow
Solution 3 - JavascriptEugene IlyushinView Answer on Stackoverflow
Solution 4 - JavascriptAliaksandr SushkevichView Answer on Stackoverflow