I am using the following logic to get the i18n string of the given key.
export function i18n(key) { if (entries.hasOwnProperty(key)) { return entries[key]; } else if (typeof (Canadarm) !== 'undefined') { try { throw Error(); } catch (e) { Canadarm.error(entries['dataBuildI18nString'] + key, e); } } return entries[key]; } I am using ESLint in my project. I am getting the following error:
Do not access Object.prototype method 'hasOwnProperty' from target object. It is a 'no-prototype-builtins' error.
How do I change my code to resolve this error ? I don't want to disable this rule.
45 Answers
You can access it via Object.prototype:
Object.prototype.hasOwnProperty.call(obj, prop); That should be safer, because
- Not all objects inherit from
Object.prototype - Even for objects which inherit from
Object.prototype, thehasOwnPropertymethod could be shadowed by something else.
Of course, the code above assumes that
- The global
Objecthas not been shadowed or redefined - The native
Object.prototype.hasOwnPropertyhas not been redefined - No
callown property has been added toObject.prototype.hasOwnProperty - The native
Function.prototype.callhas not been redefined
If any of these does not hold, attempting to code in a safer way, you could have broken your code!
Another approach which does not need call would be
!!Object.getOwnPropertyDescriptor(obj, prop); For your specific case, the following examples shall work:
if(Object.prototype.hasOwnProperty.call(entries, "key")) { //rest of the code } OR
if(Object.prototype.isPrototypeOf.call(entries, key)) { //rest of the code } OR
if({}.propertyIsEnumerable.call(entries, "key")) { //rest of the code } 1It seems like this would also work:
key in entries
since that will return a boolean on whether or not the key exists inside the object?
1@Orial answer is correct
Use this:
Object.prototype.hasOwnProperty.call(object, "objectProperty"); this is working for me so try with it
let bug={ name:"test" } if (bug && typeof bug === 'object' && Object.prototype.hasOwnProperty.call(bug, name)) { }
1