在 Javascript 中,如何判断一个字段是否存在于一个对象中?

当然,我希望在代码方面做到这一点。并不是说我面临的问题没有其他选择,只是好奇。

116001 次浏览

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) {
}

This will ignore attributes passed down through the prototype chain.

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

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

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

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

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

This question is quite old but it still can be useful to some people.

Now, there is an other way to do it which is recommended if you have non-hardcoded keys.

You have to go from this:

foo.hasOwnProperty("bar");

To this:

Object.prototype.hasOwnProperty.call(foo, "bar");

This update is particularly useful, especially if you use a linter like ESLint which has by default this rule in the "eslint:recommended" set of rules. This new way to do it is notably for security reasons. The whole explanation is available on this page.