16

I'm trying to get the keys from a JavaScript Object. When I inspect the object I can see that there is a key value pair on the object but when I run Object.keys(myObject) I get an empty array returned. What am I doing wrong?

enter image description here

I'm following this documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

And the function which creates the object is as follows:

query: function () {
  var query = {}
  _.each(this.$el.find('input:checked'), function (el, index) {
    Object.defineProperty(query, el.id, {value: el.value})
  })
  return query
}
4
  • 8
    Object.keys only returns enumerable own keys. Try Object.getOwnPropertyNames. Commented Nov 5, 2015 at 18:10
  • OMG thanks. you saved me a whole lot of pain & head scratching Commented Nov 5, 2015 at 18:14
  • I can't find a duplicate - so I'll post it as an answer. Commented Nov 5, 2015 at 18:15
  • stackoverflow.com/questions/22658488/… Commented Nov 5, 2015 at 18:19

2 Answers 2

20

Object.keys only returns enumerable own keys. Try Object.getOwnPropertyNames.

Sign up to request clarification or add additional context in comments.

Comments

7

Console.log prints the most recent value of its contents and not the value of that content at that specific time of execution.

To log the array, try deep-cloning its value to another variable and then console log it.

 console.log(JSON.parse(JSON.stringify(keys)));

1 Comment

This answer deserves way more credit. Thank you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.