Get array of object's keysHow to get collection of keys in javascript dictionary?HashMap objects in javascriptForm array of property names found in a JavaScript ObjectHow to access all JSON array nameHow to access the item in an object of an array by index number?Javascript extract object names to an arrayParsing JSON keys into array of stringsBasic «reflection» in JSHow to convert an Object to an Array [] in JavaScriptAssign object variable name to a variable javascript or typescriptHow do you get a timestamp in JavaScript?How do I check if an array includes an object in JavaScript?Get the name of an object's typeHow to append something to an array?How do you check if a variable is an array in JavaScript?Checking if a key exists in a JavaScript object?Loop through an array in JavaScriptHow do I remove a particular element from an array in JavaScript?For-each over an array in JavaScript?JavaScript set object key by variable
Has the Hulk always been able to talk?
Why does sound not move through a wall?
How do I allocate more memory to an app on Sheepshaver running Mac OS 9?
All of my Firefox add-ons been disabled suddenly, how can I re-enable them?
How to stop bricks pushing out while drilling?
How can Internet speed be 10 times slower without a router than when using the same connection with a router?
How to deal with employer who keeps me at work after working hours
My large rocket is still flipping over
Is there a word that describes the unjustified use of a more complex word?
Where are the "shires" in the UK?
As a GM, is it bad form to ask for a moment to think when improvising?
In linear regression why does regularisation penalise the parameter values as well?
Constitutional limitation of criminalizing behavior in US law?
As black, how should one respond to 4. Qe2 by white in the Russian Game, Damiano Variation?
Should I simplify my writing in a foreign country?
Clarification of algebra in moment generating functions
Undefined Control Sequence for my 0-norm
What do you call a painting on a wall?
Is there an age requirement to play in Adventurers League?
Motion-trail-like lines
Hostile Divisor Numbers
The origin of list data structure
Meaning of the (idiomatic?) expression "seghe mentali"
How to pass query parameters in URL in Salesforce Summer 19 Release?
Get array of object's keys
How to get collection of keys in javascript dictionary?HashMap objects in javascriptForm array of property names found in a JavaScript ObjectHow to access all JSON array nameHow to access the item in an object of an array by index number?Javascript extract object names to an arrayParsing JSON keys into array of stringsBasic «reflection» in JSHow to convert an Object to an Array [] in JavaScriptAssign object variable name to a variable javascript or typescriptHow do you get a timestamp in JavaScript?How do I check if an array includes an object in JavaScript?Get the name of an object's typeHow to append something to an array?How do you check if a variable is an array in JavaScript?Checking if a key exists in a JavaScript object?Loop through an array in JavaScriptHow do I remove a particular element from an array in JavaScript?For-each over an array in JavaScript?JavaScript set object key by variable
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
I would like to get the keys of a JavaScript object as an array, either in jQuery or pure JavaScript.
Is there a less verbose way than this?
var foo = 'alpha' : 'puffin', 'beta' : 'beagle' ;
var keys = [];
for (var key in foo)
keys.push(key);
javascript ecmascript-5
add a comment |
I would like to get the keys of a JavaScript object as an array, either in jQuery or pure JavaScript.
Is there a less verbose way than this?
var foo = 'alpha' : 'puffin', 'beta' : 'beagle' ;
var keys = [];
for (var key in foo)
keys.push(key);
javascript ecmascript-5
4
Besides from addingif(foo.hasOwnProperty(key))
, that's what I'd do. Or, use$.map
.
– Rocket Hazmat
Jan 6 '12 at 19:17
9
Oh for a Pythonic one-liner, though...
– Richard
Jan 6 '12 at 19:17
an old question so not worth a full answer, but for those who want to fiddle... jsfiddle.net/LR5D9/3 this solution deals with the issue of prototype declarations messing upfor var in x
loops
– unsynchronized
Jul 13 '14 at 1:56
add a comment |
I would like to get the keys of a JavaScript object as an array, either in jQuery or pure JavaScript.
Is there a less verbose way than this?
var foo = 'alpha' : 'puffin', 'beta' : 'beagle' ;
var keys = [];
for (var key in foo)
keys.push(key);
javascript ecmascript-5
I would like to get the keys of a JavaScript object as an array, either in jQuery or pure JavaScript.
Is there a less verbose way than this?
var foo = 'alpha' : 'puffin', 'beta' : 'beagle' ;
var keys = [];
for (var key in foo)
keys.push(key);
javascript ecmascript-5
javascript ecmascript-5
edited Jan 12 '18 at 21:45
dreftymac
16.4k2191154
16.4k2191154
asked Jan 6 '12 at 19:12
RichardRichard
10.9k2391141
10.9k2391141
4
Besides from addingif(foo.hasOwnProperty(key))
, that's what I'd do. Or, use$.map
.
– Rocket Hazmat
Jan 6 '12 at 19:17
9
Oh for a Pythonic one-liner, though...
– Richard
Jan 6 '12 at 19:17
an old question so not worth a full answer, but for those who want to fiddle... jsfiddle.net/LR5D9/3 this solution deals with the issue of prototype declarations messing upfor var in x
loops
– unsynchronized
Jul 13 '14 at 1:56
add a comment |
4
Besides from addingif(foo.hasOwnProperty(key))
, that's what I'd do. Or, use$.map
.
– Rocket Hazmat
Jan 6 '12 at 19:17
9
Oh for a Pythonic one-liner, though...
– Richard
Jan 6 '12 at 19:17
an old question so not worth a full answer, but for those who want to fiddle... jsfiddle.net/LR5D9/3 this solution deals with the issue of prototype declarations messing upfor var in x
loops
– unsynchronized
Jul 13 '14 at 1:56
4
4
Besides from adding
if(foo.hasOwnProperty(key))
, that's what I'd do. Or, use $.map
.– Rocket Hazmat
Jan 6 '12 at 19:17
Besides from adding
if(foo.hasOwnProperty(key))
, that's what I'd do. Or, use $.map
.– Rocket Hazmat
Jan 6 '12 at 19:17
9
9
Oh for a Pythonic one-liner, though...
– Richard
Jan 6 '12 at 19:17
Oh for a Pythonic one-liner, though...
– Richard
Jan 6 '12 at 19:17
an old question so not worth a full answer, but for those who want to fiddle... jsfiddle.net/LR5D9/3 this solution deals with the issue of prototype declarations messing up
for var in x
loops– unsynchronized
Jul 13 '14 at 1:56
an old question so not worth a full answer, but for those who want to fiddle... jsfiddle.net/LR5D9/3 this solution deals with the issue of prototype declarations messing up
for var in x
loops– unsynchronized
Jul 13 '14 at 1:56
add a comment |
7 Answers
7
active
oldest
votes
Use Object.keys
:
var foo =
'alpha': 'puffin',
'beta': 'beagle'
;
var keys = Object.keys(foo);
console.log(keys) // ['alpha', 'beta']
// (or maybe some other order, keys are unordered).
This is an ES5 feature. This means it works in all modern browsers but will not work in legacy browsers.
The ES5-shim has a implementation of Object.keys
you can steal
5
Note: This only works on modern browsers (by that I mean not IE < 9).
– Rocket Hazmat
Jan 6 '12 at 19:21
2
And what about mobile browsers ?
– Marwen Trabelsi
Aug 7 '14 at 8:15
1
@SmartyTwiti: I'm not sure. I'd assume it does in like Chrome or Firefox.
– Rocket Hazmat
Aug 7 '14 at 15:17
MDN also has the above referred Polyfill, but notes bugs in IE7 and maybe 8, then refers off to a much shorter Polyfill here: tokenposts.blogspot.com.au/2012/04/…
– Campbeln
Jan 21 '15 at 23:17
This works in all mobile browsers Can I Use?
– Edward Wall
Jun 21 '18 at 5:44
|
show 1 more comment
You can use jQuery's $.map
.
var foo = 'alpha' : 'puffin', 'beta' : 'beagle' ,
keys = $.map(foo, function(v, i)
return i;
);
2
This solution (Rocket's) works fine jsfiddle.net/KV3RA/3
– MilkyWayJoe
Jan 6 '12 at 19:41
3
Seems to me this solution is much better if Object.keys() doesn't work in IE8...
– NLemay
Jan 10 '14 at 21:52
add a comment |
Of course, Object.keys()
is the best way to get an Object's keys. If it's not available in your environment, it can be trivially shimmed using code such as in your example (except you'd need to take into account your loop will iterate over all properties up the prototype chain, unlike Object.keys()
's behaviour).
However, your example code...
var foo = 'alpha' : 'puffin', 'beta' : 'beagle' ;
var keys = [];
for (var key in foo)
keys.push(key);
jsFiddle.
...could be modified. You can do the assignment right in the variable part.
var foo = 'alpha' : 'puffin', 'beta' : 'beagle' ;
var keys = [], i = 0;
for (keys[i++] in foo)
jsFiddle.
Of course, this behaviour is different to what Object.keys()
actually does (jsFiddle). You could simply use the shim on the MDN documentation.
8
I liked thisvar keys = [], i = 0; for (keys[i++] in foo)
+1
– Jashwant
Feb 1 '13 at 12:42
I heard that "for in" doesn't guarantee order, do you know if Object.keys does?
– Chris Stephens
May 13 '13 at 19:06
@ChrisStephens Neither guarantee order, even if the keys end up being in an ordered array.
– alex
May 13 '13 at 23:49
2
all of these solutions need ahasOwnProperty()
check, surely?
– unsynchronized
Jul 13 '14 at 0:38
1
@TIMINeutron There's no reason why it shouldn't :)
– alex
Dec 18 '14 at 22:31
|
show 5 more comments
I don't know about less verbose but I was inspired to coerce the following onto one line by the one-liner request, don't know how Pythonic it is though ;)
var keys = (function(o)var ks=[]; for(var k in o) ks.push(k); return ks)(foo);
3
Maybe that should bevar enumerableKeysOnThePrototypeChain
;)
– alex
May 13 '13 at 23:51
1
Maybe we're smart enough to know we don't have to worry about hasOwnProperty if the object is created entirely under our purview as opposed to being imported from somewhere else
– George Jempty
Jan 21 '16 at 17:35
not as pythonic as @alex's 2nd answer (for (keys[i++] in foo)
) though, because you're still performingArray.push()
(not to mention declaring a whole function). A pythonic implementation should rely as much on implicit comprehension as possible, and failing that, using a lambda expression.
– cowbert
Sep 28 '17 at 21:10
@cowbert ok thanks for your observation
– George Jempty
Sep 29 '17 at 14:32
add a comment |
Summary
For getting all of the keys of an Object you can use Object.keys()
. Object.keys()
takes an object as an argument and returns an array of all the keys.
Example:
const object =
a: 'string1',
b: 42,
c: 34
;
const keys = Object.keys(object)
console.log(keys);
console.log(keys.length) // we can easily access the total amount of properties the object has
In the above example we store an array of keys in the keys const. We then can easily access the amount of properties on the object by checking the length of the keys array.
Getting the values with: Object.values()
The complementary function of Object.keys()
is Object.values()
. This function takes an object as an argument and returns an array of values. For example:
const object =
a: 'random',
b: 22,
c: true
;
console.log(Object.values(object));
add a comment |
If you decide to use Underscore.js you better do
var foo = 'alpha' : 'puffin', 'beta' : 'beagle' ;
var keys = [];
_.each( foo, function( val, key )
keys.push(key);
);
console.log(keys);
add a comment |
In case you're here looking for something to list the keys of an n-depth nested object as a flat array:
const getObjectKeys = (obj, prefix = '') =>
return Object.entries(obj).reduce((collector, [key, val]) =>
const newKeys = [ ...collector, prefix ? `$prefix.$key` : key ]
if (Object.prototype.toString.call(val) === '[object Object]')
const newPrefix = prefix ? `$prefix.$key` : key
const otherKeys = getObjectKeys(val, newPrefix)
return [ ...newKeys, ...otherKeys ]
return newKeys
, [])
console.log(getObjectKeys(a: 1, b: 2, c: d: 3, e: f: 4 ))
add a comment |
protected by Community♦ Jun 9 '17 at 6:53
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
7 Answers
7
active
oldest
votes
7 Answers
7
active
oldest
votes
active
oldest
votes
active
oldest
votes
Use Object.keys
:
var foo =
'alpha': 'puffin',
'beta': 'beagle'
;
var keys = Object.keys(foo);
console.log(keys) // ['alpha', 'beta']
// (or maybe some other order, keys are unordered).
This is an ES5 feature. This means it works in all modern browsers but will not work in legacy browsers.
The ES5-shim has a implementation of Object.keys
you can steal
5
Note: This only works on modern browsers (by that I mean not IE < 9).
– Rocket Hazmat
Jan 6 '12 at 19:21
2
And what about mobile browsers ?
– Marwen Trabelsi
Aug 7 '14 at 8:15
1
@SmartyTwiti: I'm not sure. I'd assume it does in like Chrome or Firefox.
– Rocket Hazmat
Aug 7 '14 at 15:17
MDN also has the above referred Polyfill, but notes bugs in IE7 and maybe 8, then refers off to a much shorter Polyfill here: tokenposts.blogspot.com.au/2012/04/…
– Campbeln
Jan 21 '15 at 23:17
This works in all mobile browsers Can I Use?
– Edward Wall
Jun 21 '18 at 5:44
|
show 1 more comment
Use Object.keys
:
var foo =
'alpha': 'puffin',
'beta': 'beagle'
;
var keys = Object.keys(foo);
console.log(keys) // ['alpha', 'beta']
// (or maybe some other order, keys are unordered).
This is an ES5 feature. This means it works in all modern browsers but will not work in legacy browsers.
The ES5-shim has a implementation of Object.keys
you can steal
5
Note: This only works on modern browsers (by that I mean not IE < 9).
– Rocket Hazmat
Jan 6 '12 at 19:21
2
And what about mobile browsers ?
– Marwen Trabelsi
Aug 7 '14 at 8:15
1
@SmartyTwiti: I'm not sure. I'd assume it does in like Chrome or Firefox.
– Rocket Hazmat
Aug 7 '14 at 15:17
MDN also has the above referred Polyfill, but notes bugs in IE7 and maybe 8, then refers off to a much shorter Polyfill here: tokenposts.blogspot.com.au/2012/04/…
– Campbeln
Jan 21 '15 at 23:17
This works in all mobile browsers Can I Use?
– Edward Wall
Jun 21 '18 at 5:44
|
show 1 more comment
Use Object.keys
:
var foo =
'alpha': 'puffin',
'beta': 'beagle'
;
var keys = Object.keys(foo);
console.log(keys) // ['alpha', 'beta']
// (or maybe some other order, keys are unordered).
This is an ES5 feature. This means it works in all modern browsers but will not work in legacy browsers.
The ES5-shim has a implementation of Object.keys
you can steal
Use Object.keys
:
var foo =
'alpha': 'puffin',
'beta': 'beagle'
;
var keys = Object.keys(foo);
console.log(keys) // ['alpha', 'beta']
// (or maybe some other order, keys are unordered).
This is an ES5 feature. This means it works in all modern browsers but will not work in legacy browsers.
The ES5-shim has a implementation of Object.keys
you can steal
var foo =
'alpha': 'puffin',
'beta': 'beagle'
;
var keys = Object.keys(foo);
console.log(keys) // ['alpha', 'beta']
// (or maybe some other order, keys are unordered).
var foo =
'alpha': 'puffin',
'beta': 'beagle'
;
var keys = Object.keys(foo);
console.log(keys) // ['alpha', 'beta']
// (or maybe some other order, keys are unordered).
edited 2 days ago
adiga
13.4k62745
13.4k62745
answered Jan 6 '12 at 19:19
RaynosRaynos
135k43317374
135k43317374
5
Note: This only works on modern browsers (by that I mean not IE < 9).
– Rocket Hazmat
Jan 6 '12 at 19:21
2
And what about mobile browsers ?
– Marwen Trabelsi
Aug 7 '14 at 8:15
1
@SmartyTwiti: I'm not sure. I'd assume it does in like Chrome or Firefox.
– Rocket Hazmat
Aug 7 '14 at 15:17
MDN also has the above referred Polyfill, but notes bugs in IE7 and maybe 8, then refers off to a much shorter Polyfill here: tokenposts.blogspot.com.au/2012/04/…
– Campbeln
Jan 21 '15 at 23:17
This works in all mobile browsers Can I Use?
– Edward Wall
Jun 21 '18 at 5:44
|
show 1 more comment
5
Note: This only works on modern browsers (by that I mean not IE < 9).
– Rocket Hazmat
Jan 6 '12 at 19:21
2
And what about mobile browsers ?
– Marwen Trabelsi
Aug 7 '14 at 8:15
1
@SmartyTwiti: I'm not sure. I'd assume it does in like Chrome or Firefox.
– Rocket Hazmat
Aug 7 '14 at 15:17
MDN also has the above referred Polyfill, but notes bugs in IE7 and maybe 8, then refers off to a much shorter Polyfill here: tokenposts.blogspot.com.au/2012/04/…
– Campbeln
Jan 21 '15 at 23:17
This works in all mobile browsers Can I Use?
– Edward Wall
Jun 21 '18 at 5:44
5
5
Note: This only works on modern browsers (by that I mean not IE < 9).
– Rocket Hazmat
Jan 6 '12 at 19:21
Note: This only works on modern browsers (by that I mean not IE < 9).
– Rocket Hazmat
Jan 6 '12 at 19:21
2
2
And what about mobile browsers ?
– Marwen Trabelsi
Aug 7 '14 at 8:15
And what about mobile browsers ?
– Marwen Trabelsi
Aug 7 '14 at 8:15
1
1
@SmartyTwiti: I'm not sure. I'd assume it does in like Chrome or Firefox.
– Rocket Hazmat
Aug 7 '14 at 15:17
@SmartyTwiti: I'm not sure. I'd assume it does in like Chrome or Firefox.
– Rocket Hazmat
Aug 7 '14 at 15:17
MDN also has the above referred Polyfill, but notes bugs in IE7 and maybe 8, then refers off to a much shorter Polyfill here: tokenposts.blogspot.com.au/2012/04/…
– Campbeln
Jan 21 '15 at 23:17
MDN also has the above referred Polyfill, but notes bugs in IE7 and maybe 8, then refers off to a much shorter Polyfill here: tokenposts.blogspot.com.au/2012/04/…
– Campbeln
Jan 21 '15 at 23:17
This works in all mobile browsers Can I Use?
– Edward Wall
Jun 21 '18 at 5:44
This works in all mobile browsers Can I Use?
– Edward Wall
Jun 21 '18 at 5:44
|
show 1 more comment
You can use jQuery's $.map
.
var foo = 'alpha' : 'puffin', 'beta' : 'beagle' ,
keys = $.map(foo, function(v, i)
return i;
);
2
This solution (Rocket's) works fine jsfiddle.net/KV3RA/3
– MilkyWayJoe
Jan 6 '12 at 19:41
3
Seems to me this solution is much better if Object.keys() doesn't work in IE8...
– NLemay
Jan 10 '14 at 21:52
add a comment |
You can use jQuery's $.map
.
var foo = 'alpha' : 'puffin', 'beta' : 'beagle' ,
keys = $.map(foo, function(v, i)
return i;
);
2
This solution (Rocket's) works fine jsfiddle.net/KV3RA/3
– MilkyWayJoe
Jan 6 '12 at 19:41
3
Seems to me this solution is much better if Object.keys() doesn't work in IE8...
– NLemay
Jan 10 '14 at 21:52
add a comment |
You can use jQuery's $.map
.
var foo = 'alpha' : 'puffin', 'beta' : 'beagle' ,
keys = $.map(foo, function(v, i)
return i;
);
You can use jQuery's $.map
.
var foo = 'alpha' : 'puffin', 'beta' : 'beagle' ,
keys = $.map(foo, function(v, i)
return i;
);
answered Jan 6 '12 at 19:18
Rocket HazmatRocket Hazmat
171k31248300
171k31248300
2
This solution (Rocket's) works fine jsfiddle.net/KV3RA/3
– MilkyWayJoe
Jan 6 '12 at 19:41
3
Seems to me this solution is much better if Object.keys() doesn't work in IE8...
– NLemay
Jan 10 '14 at 21:52
add a comment |
2
This solution (Rocket's) works fine jsfiddle.net/KV3RA/3
– MilkyWayJoe
Jan 6 '12 at 19:41
3
Seems to me this solution is much better if Object.keys() doesn't work in IE8...
– NLemay
Jan 10 '14 at 21:52
2
2
This solution (Rocket's) works fine jsfiddle.net/KV3RA/3
– MilkyWayJoe
Jan 6 '12 at 19:41
This solution (Rocket's) works fine jsfiddle.net/KV3RA/3
– MilkyWayJoe
Jan 6 '12 at 19:41
3
3
Seems to me this solution is much better if Object.keys() doesn't work in IE8...
– NLemay
Jan 10 '14 at 21:52
Seems to me this solution is much better if Object.keys() doesn't work in IE8...
– NLemay
Jan 10 '14 at 21:52
add a comment |
Of course, Object.keys()
is the best way to get an Object's keys. If it's not available in your environment, it can be trivially shimmed using code such as in your example (except you'd need to take into account your loop will iterate over all properties up the prototype chain, unlike Object.keys()
's behaviour).
However, your example code...
var foo = 'alpha' : 'puffin', 'beta' : 'beagle' ;
var keys = [];
for (var key in foo)
keys.push(key);
jsFiddle.
...could be modified. You can do the assignment right in the variable part.
var foo = 'alpha' : 'puffin', 'beta' : 'beagle' ;
var keys = [], i = 0;
for (keys[i++] in foo)
jsFiddle.
Of course, this behaviour is different to what Object.keys()
actually does (jsFiddle). You could simply use the shim on the MDN documentation.
8
I liked thisvar keys = [], i = 0; for (keys[i++] in foo)
+1
– Jashwant
Feb 1 '13 at 12:42
I heard that "for in" doesn't guarantee order, do you know if Object.keys does?
– Chris Stephens
May 13 '13 at 19:06
@ChrisStephens Neither guarantee order, even if the keys end up being in an ordered array.
– alex
May 13 '13 at 23:49
2
all of these solutions need ahasOwnProperty()
check, surely?
– unsynchronized
Jul 13 '14 at 0:38
1
@TIMINeutron There's no reason why it shouldn't :)
– alex
Dec 18 '14 at 22:31
|
show 5 more comments
Of course, Object.keys()
is the best way to get an Object's keys. If it's not available in your environment, it can be trivially shimmed using code such as in your example (except you'd need to take into account your loop will iterate over all properties up the prototype chain, unlike Object.keys()
's behaviour).
However, your example code...
var foo = 'alpha' : 'puffin', 'beta' : 'beagle' ;
var keys = [];
for (var key in foo)
keys.push(key);
jsFiddle.
...could be modified. You can do the assignment right in the variable part.
var foo = 'alpha' : 'puffin', 'beta' : 'beagle' ;
var keys = [], i = 0;
for (keys[i++] in foo)
jsFiddle.
Of course, this behaviour is different to what Object.keys()
actually does (jsFiddle). You could simply use the shim on the MDN documentation.
8
I liked thisvar keys = [], i = 0; for (keys[i++] in foo)
+1
– Jashwant
Feb 1 '13 at 12:42
I heard that "for in" doesn't guarantee order, do you know if Object.keys does?
– Chris Stephens
May 13 '13 at 19:06
@ChrisStephens Neither guarantee order, even if the keys end up being in an ordered array.
– alex
May 13 '13 at 23:49
2
all of these solutions need ahasOwnProperty()
check, surely?
– unsynchronized
Jul 13 '14 at 0:38
1
@TIMINeutron There's no reason why it shouldn't :)
– alex
Dec 18 '14 at 22:31
|
show 5 more comments
Of course, Object.keys()
is the best way to get an Object's keys. If it's not available in your environment, it can be trivially shimmed using code such as in your example (except you'd need to take into account your loop will iterate over all properties up the prototype chain, unlike Object.keys()
's behaviour).
However, your example code...
var foo = 'alpha' : 'puffin', 'beta' : 'beagle' ;
var keys = [];
for (var key in foo)
keys.push(key);
jsFiddle.
...could be modified. You can do the assignment right in the variable part.
var foo = 'alpha' : 'puffin', 'beta' : 'beagle' ;
var keys = [], i = 0;
for (keys[i++] in foo)
jsFiddle.
Of course, this behaviour is different to what Object.keys()
actually does (jsFiddle). You could simply use the shim on the MDN documentation.
Of course, Object.keys()
is the best way to get an Object's keys. If it's not available in your environment, it can be trivially shimmed using code such as in your example (except you'd need to take into account your loop will iterate over all properties up the prototype chain, unlike Object.keys()
's behaviour).
However, your example code...
var foo = 'alpha' : 'puffin', 'beta' : 'beagle' ;
var keys = [];
for (var key in foo)
keys.push(key);
jsFiddle.
...could be modified. You can do the assignment right in the variable part.
var foo = 'alpha' : 'puffin', 'beta' : 'beagle' ;
var keys = [], i = 0;
for (keys[i++] in foo)
jsFiddle.
Of course, this behaviour is different to what Object.keys()
actually does (jsFiddle). You could simply use the shim on the MDN documentation.
answered Jun 8 '12 at 3:58
alexalex
348k173780916
348k173780916
8
I liked thisvar keys = [], i = 0; for (keys[i++] in foo)
+1
– Jashwant
Feb 1 '13 at 12:42
I heard that "for in" doesn't guarantee order, do you know if Object.keys does?
– Chris Stephens
May 13 '13 at 19:06
@ChrisStephens Neither guarantee order, even if the keys end up being in an ordered array.
– alex
May 13 '13 at 23:49
2
all of these solutions need ahasOwnProperty()
check, surely?
– unsynchronized
Jul 13 '14 at 0:38
1
@TIMINeutron There's no reason why it shouldn't :)
– alex
Dec 18 '14 at 22:31
|
show 5 more comments
8
I liked thisvar keys = [], i = 0; for (keys[i++] in foo)
+1
– Jashwant
Feb 1 '13 at 12:42
I heard that "for in" doesn't guarantee order, do you know if Object.keys does?
– Chris Stephens
May 13 '13 at 19:06
@ChrisStephens Neither guarantee order, even if the keys end up being in an ordered array.
– alex
May 13 '13 at 23:49
2
all of these solutions need ahasOwnProperty()
check, surely?
– unsynchronized
Jul 13 '14 at 0:38
1
@TIMINeutron There's no reason why it shouldn't :)
– alex
Dec 18 '14 at 22:31
8
8
I liked this
var keys = [], i = 0; for (keys[i++] in foo)
+1– Jashwant
Feb 1 '13 at 12:42
I liked this
var keys = [], i = 0; for (keys[i++] in foo)
+1– Jashwant
Feb 1 '13 at 12:42
I heard that "for in" doesn't guarantee order, do you know if Object.keys does?
– Chris Stephens
May 13 '13 at 19:06
I heard that "for in" doesn't guarantee order, do you know if Object.keys does?
– Chris Stephens
May 13 '13 at 19:06
@ChrisStephens Neither guarantee order, even if the keys end up being in an ordered array.
– alex
May 13 '13 at 23:49
@ChrisStephens Neither guarantee order, even if the keys end up being in an ordered array.
– alex
May 13 '13 at 23:49
2
2
all of these solutions need a
hasOwnProperty()
check, surely?– unsynchronized
Jul 13 '14 at 0:38
all of these solutions need a
hasOwnProperty()
check, surely?– unsynchronized
Jul 13 '14 at 0:38
1
1
@TIMINeutron There's no reason why it shouldn't :)
– alex
Dec 18 '14 at 22:31
@TIMINeutron There's no reason why it shouldn't :)
– alex
Dec 18 '14 at 22:31
|
show 5 more comments
I don't know about less verbose but I was inspired to coerce the following onto one line by the one-liner request, don't know how Pythonic it is though ;)
var keys = (function(o)var ks=[]; for(var k in o) ks.push(k); return ks)(foo);
3
Maybe that should bevar enumerableKeysOnThePrototypeChain
;)
– alex
May 13 '13 at 23:51
1
Maybe we're smart enough to know we don't have to worry about hasOwnProperty if the object is created entirely under our purview as opposed to being imported from somewhere else
– George Jempty
Jan 21 '16 at 17:35
not as pythonic as @alex's 2nd answer (for (keys[i++] in foo)
) though, because you're still performingArray.push()
(not to mention declaring a whole function). A pythonic implementation should rely as much on implicit comprehension as possible, and failing that, using a lambda expression.
– cowbert
Sep 28 '17 at 21:10
@cowbert ok thanks for your observation
– George Jempty
Sep 29 '17 at 14:32
add a comment |
I don't know about less verbose but I was inspired to coerce the following onto one line by the one-liner request, don't know how Pythonic it is though ;)
var keys = (function(o)var ks=[]; for(var k in o) ks.push(k); return ks)(foo);
3
Maybe that should bevar enumerableKeysOnThePrototypeChain
;)
– alex
May 13 '13 at 23:51
1
Maybe we're smart enough to know we don't have to worry about hasOwnProperty if the object is created entirely under our purview as opposed to being imported from somewhere else
– George Jempty
Jan 21 '16 at 17:35
not as pythonic as @alex's 2nd answer (for (keys[i++] in foo)
) though, because you're still performingArray.push()
(not to mention declaring a whole function). A pythonic implementation should rely as much on implicit comprehension as possible, and failing that, using a lambda expression.
– cowbert
Sep 28 '17 at 21:10
@cowbert ok thanks for your observation
– George Jempty
Sep 29 '17 at 14:32
add a comment |
I don't know about less verbose but I was inspired to coerce the following onto one line by the one-liner request, don't know how Pythonic it is though ;)
var keys = (function(o)var ks=[]; for(var k in o) ks.push(k); return ks)(foo);
I don't know about less verbose but I was inspired to coerce the following onto one line by the one-liner request, don't know how Pythonic it is though ;)
var keys = (function(o)var ks=[]; for(var k in o) ks.push(k); return ks)(foo);
answered Jan 6 '12 at 19:29
George JemptyGeorge Jempty
7,1151162133
7,1151162133
3
Maybe that should bevar enumerableKeysOnThePrototypeChain
;)
– alex
May 13 '13 at 23:51
1
Maybe we're smart enough to know we don't have to worry about hasOwnProperty if the object is created entirely under our purview as opposed to being imported from somewhere else
– George Jempty
Jan 21 '16 at 17:35
not as pythonic as @alex's 2nd answer (for (keys[i++] in foo)
) though, because you're still performingArray.push()
(not to mention declaring a whole function). A pythonic implementation should rely as much on implicit comprehension as possible, and failing that, using a lambda expression.
– cowbert
Sep 28 '17 at 21:10
@cowbert ok thanks for your observation
– George Jempty
Sep 29 '17 at 14:32
add a comment |
3
Maybe that should bevar enumerableKeysOnThePrototypeChain
;)
– alex
May 13 '13 at 23:51
1
Maybe we're smart enough to know we don't have to worry about hasOwnProperty if the object is created entirely under our purview as opposed to being imported from somewhere else
– George Jempty
Jan 21 '16 at 17:35
not as pythonic as @alex's 2nd answer (for (keys[i++] in foo)
) though, because you're still performingArray.push()
(not to mention declaring a whole function). A pythonic implementation should rely as much on implicit comprehension as possible, and failing that, using a lambda expression.
– cowbert
Sep 28 '17 at 21:10
@cowbert ok thanks for your observation
– George Jempty
Sep 29 '17 at 14:32
3
3
Maybe that should be
var enumerableKeysOnThePrototypeChain
;)– alex
May 13 '13 at 23:51
Maybe that should be
var enumerableKeysOnThePrototypeChain
;)– alex
May 13 '13 at 23:51
1
1
Maybe we're smart enough to know we don't have to worry about hasOwnProperty if the object is created entirely under our purview as opposed to being imported from somewhere else
– George Jempty
Jan 21 '16 at 17:35
Maybe we're smart enough to know we don't have to worry about hasOwnProperty if the object is created entirely under our purview as opposed to being imported from somewhere else
– George Jempty
Jan 21 '16 at 17:35
not as pythonic as @alex's 2nd answer (
for (keys[i++] in foo)
) though, because you're still performing Array.push()
(not to mention declaring a whole function). A pythonic implementation should rely as much on implicit comprehension as possible, and failing that, using a lambda expression.– cowbert
Sep 28 '17 at 21:10
not as pythonic as @alex's 2nd answer (
for (keys[i++] in foo)
) though, because you're still performing Array.push()
(not to mention declaring a whole function). A pythonic implementation should rely as much on implicit comprehension as possible, and failing that, using a lambda expression.– cowbert
Sep 28 '17 at 21:10
@cowbert ok thanks for your observation
– George Jempty
Sep 29 '17 at 14:32
@cowbert ok thanks for your observation
– George Jempty
Sep 29 '17 at 14:32
add a comment |
Summary
For getting all of the keys of an Object you can use Object.keys()
. Object.keys()
takes an object as an argument and returns an array of all the keys.
Example:
const object =
a: 'string1',
b: 42,
c: 34
;
const keys = Object.keys(object)
console.log(keys);
console.log(keys.length) // we can easily access the total amount of properties the object has
In the above example we store an array of keys in the keys const. We then can easily access the amount of properties on the object by checking the length of the keys array.
Getting the values with: Object.values()
The complementary function of Object.keys()
is Object.values()
. This function takes an object as an argument and returns an array of values. For example:
const object =
a: 'random',
b: 22,
c: true
;
console.log(Object.values(object));
add a comment |
Summary
For getting all of the keys of an Object you can use Object.keys()
. Object.keys()
takes an object as an argument and returns an array of all the keys.
Example:
const object =
a: 'string1',
b: 42,
c: 34
;
const keys = Object.keys(object)
console.log(keys);
console.log(keys.length) // we can easily access the total amount of properties the object has
In the above example we store an array of keys in the keys const. We then can easily access the amount of properties on the object by checking the length of the keys array.
Getting the values with: Object.values()
The complementary function of Object.keys()
is Object.values()
. This function takes an object as an argument and returns an array of values. For example:
const object =
a: 'random',
b: 22,
c: true
;
console.log(Object.values(object));
add a comment |
Summary
For getting all of the keys of an Object you can use Object.keys()
. Object.keys()
takes an object as an argument and returns an array of all the keys.
Example:
const object =
a: 'string1',
b: 42,
c: 34
;
const keys = Object.keys(object)
console.log(keys);
console.log(keys.length) // we can easily access the total amount of properties the object has
In the above example we store an array of keys in the keys const. We then can easily access the amount of properties on the object by checking the length of the keys array.
Getting the values with: Object.values()
The complementary function of Object.keys()
is Object.values()
. This function takes an object as an argument and returns an array of values. For example:
const object =
a: 'random',
b: 22,
c: true
;
console.log(Object.values(object));
Summary
For getting all of the keys of an Object you can use Object.keys()
. Object.keys()
takes an object as an argument and returns an array of all the keys.
Example:
const object =
a: 'string1',
b: 42,
c: 34
;
const keys = Object.keys(object)
console.log(keys);
console.log(keys.length) // we can easily access the total amount of properties the object has
In the above example we store an array of keys in the keys const. We then can easily access the amount of properties on the object by checking the length of the keys array.
Getting the values with: Object.values()
The complementary function of Object.keys()
is Object.values()
. This function takes an object as an argument and returns an array of values. For example:
const object =
a: 'random',
b: 22,
c: true
;
console.log(Object.values(object));
const object =
a: 'string1',
b: 42,
c: 34
;
const keys = Object.keys(object)
console.log(keys);
console.log(keys.length) // we can easily access the total amount of properties the object has
const object =
a: 'string1',
b: 42,
c: 34
;
const keys = Object.keys(object)
console.log(keys);
console.log(keys.length) // we can easily access the total amount of properties the object has
const object =
a: 'random',
b: 22,
c: true
;
console.log(Object.values(object));
const object =
a: 'random',
b: 22,
c: true
;
console.log(Object.values(object));
answered Aug 17 '18 at 8:39
Willem van der VeenWillem van der Veen
5,84133440
5,84133440
add a comment |
add a comment |
If you decide to use Underscore.js you better do
var foo = 'alpha' : 'puffin', 'beta' : 'beagle' ;
var keys = [];
_.each( foo, function( val, key )
keys.push(key);
);
console.log(keys);
add a comment |
If you decide to use Underscore.js you better do
var foo = 'alpha' : 'puffin', 'beta' : 'beagle' ;
var keys = [];
_.each( foo, function( val, key )
keys.push(key);
);
console.log(keys);
add a comment |
If you decide to use Underscore.js you better do
var foo = 'alpha' : 'puffin', 'beta' : 'beagle' ;
var keys = [];
_.each( foo, function( val, key )
keys.push(key);
);
console.log(keys);
If you decide to use Underscore.js you better do
var foo = 'alpha' : 'puffin', 'beta' : 'beagle' ;
var keys = [];
_.each( foo, function( val, key )
keys.push(key);
);
console.log(keys);
answered Jan 9 at 6:04
mohammad javad ahmadimohammad javad ahmadi
150111
150111
add a comment |
add a comment |
In case you're here looking for something to list the keys of an n-depth nested object as a flat array:
const getObjectKeys = (obj, prefix = '') =>
return Object.entries(obj).reduce((collector, [key, val]) =>
const newKeys = [ ...collector, prefix ? `$prefix.$key` : key ]
if (Object.prototype.toString.call(val) === '[object Object]')
const newPrefix = prefix ? `$prefix.$key` : key
const otherKeys = getObjectKeys(val, newPrefix)
return [ ...newKeys, ...otherKeys ]
return newKeys
, [])
console.log(getObjectKeys(a: 1, b: 2, c: d: 3, e: f: 4 ))
add a comment |
In case you're here looking for something to list the keys of an n-depth nested object as a flat array:
const getObjectKeys = (obj, prefix = '') =>
return Object.entries(obj).reduce((collector, [key, val]) =>
const newKeys = [ ...collector, prefix ? `$prefix.$key` : key ]
if (Object.prototype.toString.call(val) === '[object Object]')
const newPrefix = prefix ? `$prefix.$key` : key
const otherKeys = getObjectKeys(val, newPrefix)
return [ ...newKeys, ...otherKeys ]
return newKeys
, [])
console.log(getObjectKeys(a: 1, b: 2, c: d: 3, e: f: 4 ))
add a comment |
In case you're here looking for something to list the keys of an n-depth nested object as a flat array:
const getObjectKeys = (obj, prefix = '') =>
return Object.entries(obj).reduce((collector, [key, val]) =>
const newKeys = [ ...collector, prefix ? `$prefix.$key` : key ]
if (Object.prototype.toString.call(val) === '[object Object]')
const newPrefix = prefix ? `$prefix.$key` : key
const otherKeys = getObjectKeys(val, newPrefix)
return [ ...newKeys, ...otherKeys ]
return newKeys
, [])
console.log(getObjectKeys(a: 1, b: 2, c: d: 3, e: f: 4 ))
In case you're here looking for something to list the keys of an n-depth nested object as a flat array:
const getObjectKeys = (obj, prefix = '') =>
return Object.entries(obj).reduce((collector, [key, val]) =>
const newKeys = [ ...collector, prefix ? `$prefix.$key` : key ]
if (Object.prototype.toString.call(val) === '[object Object]')
const newPrefix = prefix ? `$prefix.$key` : key
const otherKeys = getObjectKeys(val, newPrefix)
return [ ...newKeys, ...otherKeys ]
return newKeys
, [])
console.log(getObjectKeys(a: 1, b: 2, c: d: 3, e: f: 4 ))
const getObjectKeys = (obj, prefix = '') =>
return Object.entries(obj).reduce((collector, [key, val]) =>
const newKeys = [ ...collector, prefix ? `$prefix.$key` : key ]
if (Object.prototype.toString.call(val) === '[object Object]')
const newPrefix = prefix ? `$prefix.$key` : key
const otherKeys = getObjectKeys(val, newPrefix)
return [ ...newKeys, ...otherKeys ]
return newKeys
, [])
console.log(getObjectKeys(a: 1, b: 2, c: d: 3, e: f: 4 ))
const getObjectKeys = (obj, prefix = '') =>
return Object.entries(obj).reduce((collector, [key, val]) =>
const newKeys = [ ...collector, prefix ? `$prefix.$key` : key ]
if (Object.prototype.toString.call(val) === '[object Object]')
const newPrefix = prefix ? `$prefix.$key` : key
const otherKeys = getObjectKeys(val, newPrefix)
return [ ...newKeys, ...otherKeys ]
return newKeys
, [])
console.log(getObjectKeys(a: 1, b: 2, c: d: 3, e: f: 4 ))
edited Mar 23 at 3:10
answered Mar 23 at 2:41
Cody MonizCody Moniz
2,16521617
2,16521617
add a comment |
add a comment |
protected by Community♦ Jun 9 '17 at 6:53
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
4
Besides from adding
if(foo.hasOwnProperty(key))
, that's what I'd do. Or, use$.map
.– Rocket Hazmat
Jan 6 '12 at 19:17
9
Oh for a Pythonic one-liner, though...
– Richard
Jan 6 '12 at 19:17
an old question so not worth a full answer, but for those who want to fiddle... jsfiddle.net/LR5D9/3 this solution deals with the issue of prototype declarations messing up
for var in x
loops– unsynchronized
Jul 13 '14 at 1:56