0

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

Ramon
  • 1
  • 1
  • 2
    This arbitrary restriction makes no sense. Why would you prevent using the language? – Bergi Aug 21 '22 at 13:59
  • It sounds like the actual challenge is to find a loophole in the restriction. Are `Reflect` methods allowed (despite being built-in as well) if only Array and Object methods are forbidden? Is it allowed to disable the linter? Is it possible to trick the linter by using different syntax? – Bergi Aug 21 '22 at 14:02
  • [Object.getOwnPropertyNames](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames)? – KooiInc Aug 21 '22 at 14:02
  • 2
    "*There is a task/challenge*" - can you link the source please? – Bergi Aug 21 '22 at 14:03
  • Sorry, it's a document, not some online challenge. The task sounds stupid, that is why I'm asking. Just wanted to check if maybe I'm missing something before addressing the task author. Basically, all methods are object methods, even for example string.split(''), because str has an object in proto... I will probably disable this lint rule at the end Write function, which returns array of keys of an object. getKeys({keyOne: 1, keyTwo: 2, keyThree: 3}) // returns [“keyOne”, “keyTwo”, “keyThree”] • Using any built–in array or object methods(besides push) • Using any external libraries – Ramon Aug 21 '22 at 14:58

1 Answers1

2

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)
Brother58697
  • 2,290
  • 2
  • 4
  • 12