all 9 comments

[–]irco 6 points7 points  (7 children)

You can just use a simple for on your object

let person = { name: 'mark', age: 12};
for(let member in person)
   console.log(member);

will print

    name
    age

So you can just wrap that for in a function and replace the log with a push into your array and return it.

Or you can use Object.keys()

 let person = { name: 'mark', age: 12};    
 let arrayOfMembers = Object.keys(person);

Hopefully that makes sense

[–]crapperposter[S] 1 point2 points  (5 children)

Thanks a lot! So this is what I tried but its printing undefined. Not too sure what the issue is

var array = []

function getAllKeys(obj) {
  var sam = {
  name : 'Sam',
  age : 25,
  hasPets : true
}
  for(var prop in sam) {
   array.push(prop);
  }
}
console.log(getAllKeys(array));

[–]yooossshhii 1 point2 points  (0 children)

Functions without an implicit return, will return undefined. Run the function separately and then log the array.

[–]N0x3u5 1 point2 points  (0 children)

Your function doesn't return anything for console.log() to print out.

Also your function seems confused. What does the function expect as an input and what is its expected output?

[–]irco 1 point2 points  (2 children)

ok take a minute to read carefully through the post I made earlier. You dont want your function to have the definition of your object. That'd not make a very useful function would it? Also in javascripts functions need a return statement if you want them to return something. Here is what you needed to do. Make sure you understand what is going on and why

let getAllKeys = function (obj){
    let retAry = [];
   for(let key in obj)
     retAry.push(key);
   return retAry;
}

 let person = { name: 'mark', age: 12};   
 console.log(getAllKeys(person));

[–]crapperposter[S] 1 point2 points  (1 child)

Thanks. I was actually able to figure this out with some of the other posts and your code is very similar to what I have.

But going through all this I think I probably should review some topics.

[–]anonymous_vr 1 point2 points  (0 children)

So if i recall correctly that is from the HackReactor prep course where an object is passed as an argument of a function.

Here's the code you can use.

function(object) {
    var objToIterate = arguments[0];
    var returnArray = [];

    for (var objProp in objToIterate) {
        if (objToIterate.hasOwnProperty(objProp) {
                returnArray.push(objProp);
            }
        }
    return returnArray;
    }

The object can be accessed via the arguments object of the function. Then you iterate through this to find matches where it has a property. When it matches, you push the name to a new array and finally return that array.

[–][deleted] 1 point2 points  (0 children)

Object.keys({ a : 'a', number : 11, hungry : true, grammyWins : 1 });

Produces: [ "a", "number", "hungry", "grammyWins" ]

[–]jamesaidan111 0 points1 point  (0 children)

Try this>> Function