How do I check if a variable contains a certain property?
Let’s assume:
var x = 'some string';
Then I would like to do:
if ('trim' in x)
but that gives me a:
Uncaught TypeError: Cannot use 'in' operator to search for 'trim' in string
I can make it work by using:
'trim' in x.__proto__
but according to MDN __proto__
is deprecated and its use is (quote) "controversial and discouraged".
How can I achieve this then?
I have tried to use Object.keys(x)
but that only lists the keys that are valid as indexes, not the properties.
I know that, in this specific example, I could simply use typeof x === 'string'
but that’s not a universal solution.
3
Answers
You can verify if any variable has a property like the function
hasProperty
in the snippet below.Note that you can use
Reflect.has(obj, prop)
. But ifobj
do not passobj instanceof Object
then an exception will be thrown, which is what happens when usingmySubject1
,mySubject2
ormySubject4
as theobj
parameter.If for some reason you want to avoid directly accessing the property via
x[prop]
, you could first pass the value to theObject
function before testing within
.The
in
operator does not work with primitive values. There is alsoReflect.has()
which does the same asin
but it also has the same limitation.However, a simple way to go around it is to pass the values through the
Object
constructor without usingnew
. Doing that will convert primitives to their wrapper classes while if the input is an object, it gets returned as-is. So,Object("a string")
is the same asnew String("a string")
butObject({ some: "object" })
is the same as{ some: "object" }
. And this will allow lookups viain
(orReflect.has()
) on those values.One caveat is that
Object(null)
orObject(undefined)
will create a plain object. Which will potentially return a false positive for something like"toString in Object(null)
. Since those two values cannot have properties, they can be excluded from the check withDemo: