¿Cómo puedo comprobar si un objeto tiene una propiedad específica en JavaScript?
Considere:
x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
//Do this
}
¿Es la mejor manera de hacerlo?
if (x.key !== undefined)
Armin Ronacher parece que ya se ha adelantado a mí, pero:
Object.prototype.hasOwnProperty = function(property) {
return this[property] !== undefined;
};
x = {'key': 1};
if (x.hasOwnProperty('key')) {
alert('have key!');
}
if (!x.hasOwnProperty('bar')) {
alert('no bar!');
}
Una solución más segura, pero más lenta, como señalaron Konrad Rudolph y Armin Ronacher sería:
Object.prototype.hasOwnProperty = function(property) {
return typeof this[property] !== 'undefined';
};
Sí, lo es :) Creo que también puedes hacer Object.prototype.hasOwnProperty.call(x, 'key')
que también debería funcionar si x
tiene una propiedad llamada hasOwnProperty
:)
Pero eso comprueba las propiedades propias. Si quieres comprobar si tiene una propiedad que también puede ser heredada puedes usar typeof x.foo != 'undefined'
.
OK, parece que tenía la respuesta correcta a menos que si no quieres propiedades heredadas:
if (x.hasOwnProperty('key'))
Aquí hay algunas otras opciones para incluir las propiedades heredadas:
if (x.key) // Quick and dirty, but it does the same thing as below.
if (x.key !== undefined)