-2
var person = {
  firstName: 'Halle',
  lastName: 'Berry',
};

function names(object){
  var arr= [];
  for (var key in object) {
    arr.push(key);
    console.log(arr)
  }
}

names(person);

This is what i have so far. I am trying to return an array containing the object person keys.

5
  • 1
    Where is function what() {} declared? What is the program currently doing, and how is it different from what you expect it to do? Commented Nov 5, 2017 at 1:02
  • 2
    Welcome to Stack Overflow. Please take the tour and read How to Ask. Commented Nov 5, 2017 at 1:02
  • 2
    Missing return statement, where is what declared? Commented Nov 5, 2017 at 1:04
  • Can you tell us which language this is (ideally by editing your question and adding the correct tag)? Commented Nov 5, 2017 at 1:12
  • Sorry I meant to put names when i called the function. I edited it. Commented Nov 5, 2017 at 1:29

1 Answer 1

0

Object#keys makes this simple:

var arr = ['a', 'b', 'c'];
console.log(Object.keys(arr)); // console: ['0', '1', '2']

Edit: By clarifying the question (thank you!) and comments received, the implementation was close: it was missing a return statement. Including hasOwnProperty is a good practice to check whether keys belong to the object (true) or are inherited (false).

function names(object){
  var arr= [];
  for (var key in object) {
    if (object.hasOwnProperty(key)) {
      arr.push(key);
    }
  }
  return arr; // this was missing
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.