Reputation: 1
There is a task/challenge to get all object keys as an array. The issue is all build-in arrays and object methods are restricted ( no Object.keys() ). I can use for in loop
function getKeys(obj) {
const keysArr = [];
for (const key in obj) {
if(obj.hasOwnProperty(key)){ //restricted native object method
keysArr.push(key);
}
}
return keysArr;
}
But there is an active linter rule https://eslint.org/docs/latest/rules/guard-for-in that requires me to put a guard on a key to check if it's not coming from the object's prototype. And I can not find any way to do it, because .hasOwnProperty is a method and as far as I know there is no alternative to it because it is browser's native code. Does anyone have an idea of how to get only the own object properties in this case?
Update: as mentioned in an answer below what they probably wanted me to do is to loop through a shallow spread copy of an object const key in {...obj}. Does the job of removing values from the prototype, but does not fix linter error. Error the task itself. Thank you all for your answers
Upvotes: 0
Views: 422
Reputation: 3168
You can spread the object and loop over the result:
let obj = {foo: true}
let prototype = {bar: true}
Object.setPrototypeOf(obj, prototype)
const keysArr = [];
for (let key in {...obj}) {
keysArr.push(key)
}
console.log(keysArr)
Upvotes: 2