0

How would I write the code below as function and not using the built in Object.keys() method? Thank you!

var obj = { Name: 'Joe', Age: 18, pass: true };
console.log(Object.keys(obj)); // =>  [ 'Name', 'Age', 'pass' ]
  • See polyfill [here](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Object/keys) – Anson Feb 18 '17 at 07:54

2 Answers2

2

Do you mean this?

function getKeys(obj){
  return Object.keys(obj)
}

or

function getKeys(){
    var keys = [];
    for (var key in foo) {
        keys.push(key);
    }
    return keys;
}

or you can do

Object.prototype.getKeys = function(o, f, ctx) {
    return Object.keys(o);
}
// obj.getKeys() => [ 'Name', 'Age', 'pass' ]
Shayan
  • 956
  • 9
  • 20
  • Is it possible to write as a function without using the Object.keys in the code at all? – learninghowtocode Feb 18 '17 at 07:48
  • @learninghowtocode you mean you want something like `obj.getKeys()` ?? – Shayan Feb 18 '17 at 07:49
  • why are you so against Object.keys? – A. L Feb 18 '17 at 07:50
  • The third one doesn't allow for `obj.getKeys()`. You would have to set the function to `Object.prototype.getKeys` – 4castle Feb 18 '17 at 07:55
  • @4castle are you sure?? i use it in an application, and it's work. let me check, thanks for mention – Shayan Feb 18 '17 at 07:56
  • LOL! I'm not against Object Keys I'm just not supposed to use them to learn at the moment. :) Thanks @Shayan your second response was what I was looking for. Thanks for everyone's help!! Much appreciated! – learninghowtocode Feb 18 '17 at 07:57
  • you miss [`Object#hasOwnProperty`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty) check for an equvalent of [`Object.keys`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys) and some newer checks for it. – Nina Scholz Feb 18 '17 at 08:57
0

@Shayan's response here is what I was looking for:

function getKeys(){
    var keys = [];
    for (var key in foo) {
    keys.push(key);
    }
    return keys;
 }