+ 1

How can I get an array of object keys in JavaScript?

I'd need to know a way to get all the keys of an object as an array, I tried using the keys method, but it doesn't seem to work. I've understood from javaTpoint that you could get an array of object's keys using the keys method: https://www.javatpoint.com/javascript-objects and with solid understanding on Python dictionary methods it made sense. But it seems to give an error message and telling that there is no such method as "keys": https://code.sololearn.com/Wb8243OJxV4q/#js (In the example I wanted to get the keys (tomato, banaana, potato, strawberry, blueberry) as an array of strings.) What went wrong?

8th Sep 2019, 7:37 PM
Seb TheS
Seb TheS - avatar
3 Antworten
+ 18
Use it this way: const myObject = { question: "everything", answer: 42 } const keys = Object.keys(myObject);
8th Sep 2019, 9:28 PM
Burey
Burey - avatar
+ 4
Supplementing to the solution which Burey provided, I am hereby providing an explanation : Because for JavaScript class methods, there are two types : Class methods and prototypical methods, take String methods charCodeAt and fromCharCode as example: For String.prototype.charCodeAt, the function is inherited by its instance, and its returned value varies among different String instances, so we have to call the charCodeAt with an instance bound. https://www.sololearn.com/post/143486/?ref=app For String.fromCharCode, the function returns a character based on its numeric argument, and is universal over different string instances, so we call by referencing fromCharCode under the class (String). https://www.sololearn.com/post/143917/?ref=app https://code.sololearn.com/WKKkpq0efxai/?ref=app For keys, it is an Objects class method, so we call by prefixing its class (Objects). https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys P. S. Mozilla Doc is better as ref
9th Sep 2019, 12:15 AM
Gordon
Gordon - avatar
0
शंकर भाई गुजरात
16th Sep 2019, 5:15 PM
Sankar Bhai
Sankar Bhai - avatar