How do I loop through or enumerate a JavaScript object?
I have a JavaScript object like the following:
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
Now I want to loop through all p
elements (p1
, p2
, p3
...) And get their keys and values. How can I do that?
I can modify the JavaScript object if necessary. My ultimate goal is to loop through some key value pairs and if possible I want to avoid using eval
.
javascript loops each
add a comment |
I have a JavaScript object like the following:
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
Now I want to loop through all p
elements (p1
, p2
, p3
...) And get their keys and values. How can I do that?
I can modify the JavaScript object if necessary. My ultimate goal is to loop through some key value pairs and if possible I want to avoid using eval
.
javascript loops each
8
I changed JSON to JavaScript (object) to avoid confusing of object literals and JSON.
– Felix Kling
Mar 29 '12 at 16:48
While iterating over collection, you should care about optimization. As it may effect page performance.
– Zaheer Ahmed
Jan 11 '14 at 20:56
Pretty Print Javascript: j11y.io/demos/prettyprint I'm a huge fan of the dump function ajaxian.com/archives/javascript-variable-dump-in-coldfusion
– Kiquenet
Sep 4 '17 at 11:34
dump function: github.com/ozmartian/js-cfdump
– Kiquenet
Sep 4 '17 at 11:48
add a comment |
I have a JavaScript object like the following:
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
Now I want to loop through all p
elements (p1
, p2
, p3
...) And get their keys and values. How can I do that?
I can modify the JavaScript object if necessary. My ultimate goal is to loop through some key value pairs and if possible I want to avoid using eval
.
javascript loops each
I have a JavaScript object like the following:
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
Now I want to loop through all p
elements (p1
, p2
, p3
...) And get their keys and values. How can I do that?
I can modify the JavaScript object if necessary. My ultimate goal is to loop through some key value pairs and if possible I want to avoid using eval
.
javascript loops each
javascript loops each
edited Sep 13 '18 at 10:26


Luca Kiebel
7,53541532
7,53541532
asked Mar 26 '09 at 6:01
TanmoyTanmoy
15.6k133949
15.6k133949
8
I changed JSON to JavaScript (object) to avoid confusing of object literals and JSON.
– Felix Kling
Mar 29 '12 at 16:48
While iterating over collection, you should care about optimization. As it may effect page performance.
– Zaheer Ahmed
Jan 11 '14 at 20:56
Pretty Print Javascript: j11y.io/demos/prettyprint I'm a huge fan of the dump function ajaxian.com/archives/javascript-variable-dump-in-coldfusion
– Kiquenet
Sep 4 '17 at 11:34
dump function: github.com/ozmartian/js-cfdump
– Kiquenet
Sep 4 '17 at 11:48
add a comment |
8
I changed JSON to JavaScript (object) to avoid confusing of object literals and JSON.
– Felix Kling
Mar 29 '12 at 16:48
While iterating over collection, you should care about optimization. As it may effect page performance.
– Zaheer Ahmed
Jan 11 '14 at 20:56
Pretty Print Javascript: j11y.io/demos/prettyprint I'm a huge fan of the dump function ajaxian.com/archives/javascript-variable-dump-in-coldfusion
– Kiquenet
Sep 4 '17 at 11:34
dump function: github.com/ozmartian/js-cfdump
– Kiquenet
Sep 4 '17 at 11:48
8
8
I changed JSON to JavaScript (object) to avoid confusing of object literals and JSON.
– Felix Kling
Mar 29 '12 at 16:48
I changed JSON to JavaScript (object) to avoid confusing of object literals and JSON.
– Felix Kling
Mar 29 '12 at 16:48
While iterating over collection, you should care about optimization. As it may effect page performance.
– Zaheer Ahmed
Jan 11 '14 at 20:56
While iterating over collection, you should care about optimization. As it may effect page performance.
– Zaheer Ahmed
Jan 11 '14 at 20:56
Pretty Print Javascript: j11y.io/demos/prettyprint I'm a huge fan of the dump function ajaxian.com/archives/javascript-variable-dump-in-coldfusion
– Kiquenet
Sep 4 '17 at 11:34
Pretty Print Javascript: j11y.io/demos/prettyprint I'm a huge fan of the dump function ajaxian.com/archives/javascript-variable-dump-in-coldfusion
– Kiquenet
Sep 4 '17 at 11:34
dump function: github.com/ozmartian/js-cfdump
– Kiquenet
Sep 4 '17 at 11:48
dump function: github.com/ozmartian/js-cfdump
– Kiquenet
Sep 4 '17 at 11:48
add a comment |
35 Answers
35
active
oldest
votes
1 2
next
You can use the for-in
loop as shown by others. However, you also have to make sure that the key you get is an actual property of an object, and doesn't come from the prototype.
Here is the snippet:
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
for (var key in p) {
if (p.hasOwnProperty(key)) {
console.log(key + " -> " + p[key]);
}
}
27
Would propose that you change the alert line just for clarity toalert(key + " -> " + JSON.stringify(p[key]));
– Steve Midgley
Aug 18 '11 at 22:03
69
Can you explain the need for hasOwnProperty? What you mean by prototype?
– kamaci
Aug 22 '11 at 12:46
299
In javascript, every object has a bunch of built-in key-value pairs that have meta-information. When you loop through all the key-value pairs for an object you're looping through them too. hasOwnPropery() filters these out.
– danieltalsky
Jan 27 '12 at 15:56
51
Actually, For...in is not deprecated. For each...in is. But I really like the term archaeologists...I'm going to have to start using that.
– Ben Y
Feb 27 '14 at 16:08
11
each object in javascript (actually a key-value pair) has a property called__proto__
orprototype
. This property has a reference to its parent object. An object automatically inherits property from its parent. This is the reason of usinghasOwnProperty
, which signifies that we're interested in objects own property and not its parent ones.
– Zubair Alam
Aug 29 '14 at 19:01
|
show 17 more comments
Under ECMAScript 5, you can combine Object.keys()
and Array.prototype.forEach()
:
var obj = { first: "John", last: "Doe" };
Object.keys(obj).forEach(function(key) {
console.log(key, obj[key]);
});
ECMAScript 6 adds for...of
:
for (const key of Object.keys(obj)) {
console.log(key, obj[key]);
}
ECMAScript 8 adds Object.entries()
which avoids having to look up each value in the original object:
Object.entries(obj).forEach(
([key, value]) => console.log(key, value)
);
Both Object.keys()
and Object.entries()
iterate properties in the same order as a for...in
loop but ignore the prototype chain. Only the object's own enumerable properties are iterated.
18
Why didn't the standard provideObject.forEach(obj, function (value, key) {...})
? :( Certainlyobj.forEach(function...)
would be shorter and complementArray.prototype.forEach
, but that would risk having objects define their ownforEach
property. I supposeObject.keys
guards against the callback modifying the object's keys.
– David Harkness
Jun 23 '14 at 20:36
6
Object.forEach = function (obj, callback) { Object.keys(obj).forEach(function (key) { callback(obj[key], key); }); }
– David Harkness
Jun 23 '14 at 20:41
5
@DavidHarkness There is Object.entries in ES2017. There you can do the following:Object.entries(obj).map/forEach(([key, value]) => console.log(key, value))
([key, value] is array destructuring, to access both items directly. And you have to wrap the parameters in additional parens.)
– Andreas Linnert
Jul 14 '16 at 12:50
how do I getindex
of the key in json? Or if required i should use a separate counter?
– Saravanabalagi Ramachandran
Jan 22 '17 at 15:42
2
for...of
is ES6 standard, not ES2016.
– Rax Weber
Sep 6 '17 at 7:45
|
show 5 more comments
You have to use the for-in loop
But be very careful when using this kind of loop, because this will loop all the properties along the prototype chain.
Therefore, when using for-in loops, always make use of the hasOwnProperty
method to determine if the current property in iteration is really a property of the object you're checking on:
for (var prop in p) {
if (!p.hasOwnProperty(prop)) {
//The current property is not a direct property of p
continue;
}
//Do your logic with the property here
}
30
This is better than levik's solution because it allows the main logic to be only one nested loop in rather than two; making for easier to read code. Although I'd loose the the brackets around the continue; they are superfluous.
– SystemicPlural
Apr 6 '11 at 9:55
50
I would not remove the{ }
personally because anif
without them makes it a little unclear what is part of theif
and what is not. But I guess that's just a matter of opinion :)
– pimvdb
Aug 5 '11 at 12:01
31
Yes, I prefer keeping the{ }
mainly to avoid confusion if one later on needs to add something to theif
scope.
– Andreas Grech
Aug 5 '11 at 12:21
8
Reading my previous comment, I realized that I didn't use the correct terms, because I said "if scope"; but keep in mind that JavaScript only has function scope. So what I actually meant was "if block".
– Andreas Grech
Nov 11 '11 at 11:08
1
eomeroff, if you're really concerned about that, you could always do something like:Object.prototype.hasOwnProperty.call(p, prop)
However, this too can't protect against manipulations to Object.prototype...
– jordancpaul
Oct 15 '13 at 7:37
|
show 3 more comments
The question won't be complete if we don't mention about alternative methods for looping through objects.
Nowadays many well known JavaScript libraries provide their own methods for iterating over collections, i.e. over arrays, objects, and array-like objects. These methods are convenient to use and are entirely compatible with any browser.
If you work with jQuery, you may use
jQuery.each()
method. It can be used to seamlessly iterate over both objects and arrays:
$.each(obj, function(key, value) {
console.log(key, value);
});
In Underscore.js you can find method
_.each()
, which iterates over a list of elements, yielding each in turn to a supplied function (pay attention to the order of arguments in iteratee function!):
_.each(obj, function(value, key) {
console.log(key, value);
});
Lo-Dash provides several methods for iterating over object properties. Basic
_.forEach()
(or it's alias_.each()
) is useful for looping through both objects and arrays, however (!) objects withlength
property are treated like arrays, and to avoid this behavior it is suggested to use_.forIn()
and_.forOwn()
methods (these also havevalue
argument coming first):
_.forIn(obj, function(value, key) {
console.log(key, value);
});
_.forIn()
iterates over own and inherited enumerable properties of an object, while_.forOwn()
iterates only over own properties of an object (basically checking againsthasOwnProperty
function). For simple objects and object literals any of these methods will work fine.
Generally all described methods have the same behaviour with any supplied objects. Besides using native for..in
loop will usually be faster than any abstraction, such as jQuery.each()
, these methods are considerably easier to use, require less coding and provide better error handling.
4
To get to the value: $.each(obj, function (key, value) { console.log(value.title); });
– Ravi Ram
Jun 8 '13 at 14:41
2
Just funny how underscore and jquery changed parameters :)
– ppasler
Sep 8 '17 at 7:24
add a comment |
In ECMAScript 5 you have new approach in iteration fields of literal - Object.keys
More information you can see on MDN
My choice is below as a faster solution in current versions of browsers (Chrome30, IE10, FF25)
var keys = Object.keys(p),
len = keys.length,
i = 0,
prop,
value;
while (i < len) {
prop = keys[i];
value = p[prop];
i += 1;
}
You can compare performance of this approach with different implementations on jsperf.com:
- Extend Implementations
- Object keys iteration
- object literal iteration
Browser support you can see on Kangax's compat table
For old browser you have simple and full polyfill
UPD:
performance comparison for all most popular cases in this question on perfjs.info
:
object literal iteration
Indeed, I just wanted to post this method. But you beat me to it :(
– Jamie Hutber
Mar 20 '14 at 23:05
jsperf.com/object-iteration-comparison
– Jason
Oct 26 '16 at 15:02
add a comment |
You can just iterate over it like:
for (var key in p) {
alert(p[key]);
}
Note that key
will not take on the value of the property, it's just an index value.
12
This is repeated and not even entirely correct. You need to have a check of hasOwnProperty to make this work properly
– Vatsal
Jun 2 '16 at 20:18
3
I initially downvoted this based on the above comment until i realized that this answer came first, therefore is not "repeated". It is possibly incomplete but works just fine for many cases.
– billynoah
Oct 9 '18 at 15:16
add a comment |
Preface:
- Object properties can be own (the property is on the object itself) or inherited (not on the object itself, on one of its prototypes).
- Object properties can be enumerable or non-enumerable. Non-enumerable properties are left out of lots of property enumerations/arrays.
- Property names can be strings or Symbols. Properties whose names are Symbols are left out of lots of property enumerations/arrays.
Here in 2018, your options for looping through an object's properties are:
for-in
[MDN, spec] — A loop structure that loops through the names of an object's enumerable properties, including inherited ones, whose names are strings
Object.keys
[MDN, spec] — A function providing an array of the names of an object's own, enumerable properties whose names are strings.
Object.values
[MDN, spec] — A function providing an array of the values of an object's own, enumerable properties.
Object.entries
[MDN, spec] — A function providing an array of the names and values of an object's own, enumerable properties.
Object.getOwnPropertyNames
[MDN, spec] — A function providing an array of the names of an object's own properties (even non-enumerable ones) whose names are strings.
Object.getOwnPropertySymbols
[MDN, spec] — A function providing an array of the names of an object's own properties (even non-enumerable ones) whose names are Symbols.
Reflect.ownKeys
[MDN, spec] — A function providing an array of the names of an object's own properties (even non-enumerable ones), whether those names are strings or Symbols.- If you want all of an object's properties, including non-enumerable inherited ones, you need to use a loop and
Object.getPrototypeOf
[MDN, spec] and useObject.getOwnPropertyNames
,Object.getOwnPropertySymbols
, orReflect.ownKeys
on each object in the prototype chain (example at the bottom of this answer).
With all of them except for-in
, you'd use some kind of looping construct on the array (for
, for-of
, forEach
, etc.).
Examples:
for-in
:
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name in o) {
const value = o[name];
console.log(`${name} = ${value}`);
}
Object.keys
(with a for-of
loop, but you can use any looping construct):
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name of Object.keys(o)) {
const value = o[name];
console.log(`${name} = ${value}`);
}
Object.values
:
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const value of Object.values(o)) {
console.log(`${value}`);
}
Object.entries
:
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const [name, value] of Object.entries(o)) {
console.log(`${name} = ${value}`);
}
Object.getOwnPropertyNames
:
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name of Object.getOwnPropertyNames(o)) {
const value = o[name];
console.log(`${name} = ${value}`);
}
Object.getOwnPropertySymbols
:
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name of Object.getOwnPropertySymbols(o)) {
const value = o[name];
console.log(`${String(name)} = ${value}`);
}
Reflect.ownKeys
:
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name of Reflect.ownKeys(o)) {
const value = o[name];
console.log(`${String(name)} = ${value}`);
}
All properties, including inherited non-enumerable ones:
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (let depth = 0, current = o; current; ++depth, current = Object.getPrototypeOf(current)) {
for (const name of Reflect.ownKeys(current)) {
const value = o[name];
console.log(`[${depth}] ${String(name)} = ${String(value)}`);
}
}
.as-console-wrapper {
max-height: 100% !important;
}
add a comment |
Since es2015 is getting more and more popular I am posting this answer which include usage of generator and iterator to smoothly iterate through [key, value]
pairs. As it is possible in other languages for instance Ruby.
Ok here is a code:
const MyObject = {
'a': 'Hello',
'b': 'it's',
'c': 'me',
'd': 'you',
'e': 'looking',
'f': 'for',
[Symbol.iterator]: function* () {
for (const i of Object.keys(this)) {
yield [i, this[i]];
}
}
};
for (const [k, v] of MyObject) {
console.log(`Here is key ${k} and here is value ${v}`);
}
All information about how can you do an iterator and generator you can find at developer Mozilla page.
Hope It helped someone.
EDIT:
ES2017 will include Object.entries
which will make iterating over [key, value]
pairs in objects even more easier. It is now known that it will be a part of a standard according to the ts39 stage information.
I think it is time to update my answer to let it became even more fresher than it's now.
const MyObject = {
'a': 'Hello',
'b': 'it's',
'c': 'me',
'd': 'you',
'e': 'looking',
'f': 'for',
};
for (const [k, v] of Object.entries(MyObject)) {
console.log(`Here is key ${k} and here is value ${v}`);
}
You can find more about usage on
MDN page
This looks totally superfluous/unneeded to me. Would you add it to every object in your system? I thought the point of providing an iterator was so that you could do `for( const [k, v] of myObject )'. It just looks like extra code providing little additional value.
– Dean Radcliffe
Sep 28 '17 at 16:36
add a comment |
via prototype with forEach() which should skip the prototype chain properties:
Object.prototype.each = function(f) {
var obj = this
Object.keys(obj).forEach( function(key) {
f( key , obj[key] )
});
}
//print all keys and values
var obj = {a:1,b:2,c:3}
obj.each(function(key,value) { console.log(key + " " + value) });
// a 1
// b 2
// c 3
2
Be careful with the prototype:obj = { print: 1, each: 2, word: 3 }
producesTypeError: number is not a function
. UsingforEach
to match the similarArray
function may reduce the risk somewhat.
– David Harkness
Jun 23 '14 at 21:40
add a comment |
After looking through all the answers in here, hasOwnProperty isn't required for my own usage because my json object is clean; there's really no sense in adding any additional javascript processing. This is all I'm using:
for (var key in p) {
console.log(key + ' => ' + p[key]);
// key is key
// value is p[key]
}
18
Whether the JSON object is clean or not is irrelevant. If at any other time some code sets a property onObject.prototype
, then it will be enumerated byfor..in
. If you are sure you are not using any libraries that do that, then you don't need to callhasOwnProperty
.
– G-Wiz
Jan 13 '12 at 20:15
3
It can be completely clean if created withObject.create(null)
– Juan Mendes
Apr 14 '16 at 11:37
add a comment |
for(key in p) {
alert( p[key] );
}
Note: you can do this over arrays, but you'll iterate over the length
and other properties, too.
4
When using a for loop like that,key
will just take on an index value, so that will just alert 0, 1, 2, etc... You need to access p[key].
– Bryan
Mar 26 '09 at 6:07
1
It is the slowest method of array iteration in JavaScript. You can check this on your computer - Best way to iterate over Arrays in JavaScript
– Pencroff
Dec 5 '13 at 12:15
5
@Pencroff: the problem is that the question is not about looping through arrays... ;)
– Sk8erPeter
Jan 1 '14 at 0:55
This is something I don't understand on stackoverflow. Richard gave the correct answer, and he was the first one giving that answer, but he did not get any +1? @Bryanvar p = {"p1":"q","p2":"w"}; for(key in p) { alert( key ); }
is popping "p1" and "p2" in alerts, so whats wrong about that???
– Sebastian
Aug 5 '14 at 6:43
5
I think the main difference is the quality: the other answers not only tell how, but also tell the caveats (e.g., the prototype) and how to deal with those caveats. IMHO, those other answers are better than mine :).
– Richard Levasseur
Aug 6 '14 at 16:41
add a comment |
It's interesting people in these answers have touched on both Object.keys()
and for...of
but never combined them:
var map = {well:'hello', there:'!'};
for (let key of Object.keys(map))
console.log(key + ':' + map[key]);
You can't just for...of
an Object
because it's not an iterator, and for...index
or .forEach()
ing the Object.keys()
is ugly/inefficient.
I'm glad most people are refraining from for...in
(with or without checking .hasOwnProperty()
) as that's also a bit messy, so other than my answer above, I'm here to say...
You can make ordinary object associations iterate! Behaving just like Map
s with direct use of the fancy for...of
DEMO working in Chrome and FF (I assume ES6 only)
var ordinaryObject = {well:'hello', there:'!'};
for (let pair of ordinaryObject)
//key:value
console.log(pair[0] + ':' + pair[1]);
//or
for (let [key, value] of ordinaryObject)
console.log(key + ':' + value);
So long as you include my shim below:
//makes all objects iterable just like Maps!!! YAY
//iterates over Object.keys() (which already ignores prototype chain for us)
Object.prototype[Symbol.iterator] = function() {
var keys = Object.keys(this)[Symbol.iterator]();
var obj = this;
var output;
return {next:function() {
if (!(output = keys.next()).done)
output.value = [output.value, obj[output.value]];
return output;
}};
};
Without having to create a real Map object that doesn't have the nice syntactic sugar.
var trueMap = new Map([['well', 'hello'], ['there', '!']]);
for (let pair of trueMap)
console.log(pair[0] + ':' + pair[1]);
In fact, with this shim, if you still wanted to take advantage of Map's other functionality (without shimming them all in) but still wanted to use the neat object notation, since objects are now iterable you can now just make a Map from it!
//shown in demo
var realMap = new Map({well:'hello', there:'!'});
For those who don't like to shim, or mess with prototype
in general, feel free to make the function on window instead, calling it something like getObjIterator()
then;
//no prototype manipulation
function getObjIterator(obj) {
//create a dummy object instead of adding functionality to all objects
var iterator = new Object();
//give it what the shim does but as its own local property
iterator[Symbol.iterator] = function() {
var keys = Object.keys(obj)[Symbol.iterator]();
var output;
return {next:function() {
if (!(output = keys.next()).done)
output.value = [output.value, obj[output.value]];
return output;
}};
};
return iterator;
}
Now you can just call it as an ordinary function, nothing else is affected
var realMap = new Map(getObjIterator({well:'hello', there:'!'}))
or
for (let pair of getObjIterator(ordinaryObject))
There's no reason why that wouldn't work.
Welcome to the future.
1
Case in point. So long as people scroll down and find it helpful, that's all that matters. Usually it's me trying to do something, not liking the stuff I see online, end up figuring it out, then I come back to share. It's good doco, I've actually come across my own answers before googling things I completely forgot about!
– Hashbrown
Jul 22 '16 at 6:57
@HelpMeStackOverflowMyOnlyHope Personally I do not like modifying the prototypes of objects I did not define myself.
– Janus Troelsen
Sep 30 '16 at 10:19
@JanusTroelsen did you even read the whole answer?For those who don't like to shim, or mess with prototype in general, feel free to make the function on window instead, calling it something like getObjIterator() then;
– Hashbrown
Sep 30 '16 at 12:58
Note that this technique doesn't work on plain objects, but useful nonetheless.
– noɥʇʎԀʎzɐɹƆ
Jun 14 '18 at 15:17
it does work for plain objects, that's literally the whole point (as well as the variable names likeordinaryObject
for emphasis that the magic still works for those types). Did you check the demos; what isn't working for you, @noɥʇʎԀʎzɐɹƆ? (P.S. your SE profile image is boss)
– Hashbrown
Jun 15 '18 at 6:47
|
show 2 more comments
Object.keys(obj) : Array
retrieves all string-valued keys of all enumerable own (non-inherited) properties.
So it gives the same list of keys as you intend by testing each object key with hasOwnProperty. You don't need that extra test operation than and Object.keys( obj ).forEach(function( key ){})
is supposed to be faster. Let's prove it:
var uniqid = function(){
var text = "",
i = 0,
possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
for( ; i < 32; i++ ) {
text += possible.charAt( Math.floor( Math.random() * possible.length ) );
}
return text;
},
CYCLES = 100000,
obj = {},
p1,
p2,
p3,
key;
// Populate object with random properties
Array.apply( null, Array( CYCLES ) ).forEach(function(){
obj[ uniqid() ] = new Date()
});
// Approach #1
p1 = performance.now();
Object.keys( obj ).forEach(function( key ){
var waste = obj[ key ];
});
p2 = performance.now();
console.log( "Object.keys approach took " + (p2 - p1) + " milliseconds.");
// Approach #2
for( key in obj ) {
if ( obj.hasOwnProperty( key ) ) {
var waste = obj[ key ];
}
}
p3 = performance.now();
console.log( "for...in/hasOwnProperty approach took " + (p3 - p2) + " milliseconds.");
In my Firefox I have following results
- Object.keys approach took 40.21101451665163 milliseconds.
- for...in/hasOwnProperty approach took 98.26163508463651 milliseconds.
PS. on Chrome the difference even bigger http://codepen.io/dsheiko/pen/JdrqXa
PS2: In ES6 (EcmaScript 2015) you can iterate iterable object nicer:
let map = new Map().set('a', 1).set('b', 2);
for (let pair of map) {
console.log(pair);
}
// OR
let map = new Map([
[false, 'no'],
[true, 'yes'],
]);
map.forEach((value, key) => {
console.log(key, value);
});
if you don't feel like letting go of the {} notation, you can still useof
without creatingMap
s
– Hashbrown
Jun 28 '16 at 9:47
add a comment |
Here is another method to iterate through an object.
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
Object.keys(p).forEach(key => { console.log(key, p[key]) })
2
This is pretty cool, however for large objects, thefor
method might be more performant.
– Rolf
Mar 10 '18 at 0:17
add a comment |
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
for (var key in p) {
if (p.hasOwnProperty(key)) {
console.log(key + " = " + p[key]);
}
}
<p>
Output:<br>
p1 = values1<br>
p2 = values2<br>
p3 = values3
</p>
add a comment |
The Object.keys()
method returns an array of a given object's own enumerable properties. Read more about it here
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
Object.keys(p).map((key)=> console.log(key + "->" + p[key]))
1
If you get time, have a look at this: meta.stackexchange.com/q/114762
– Praveen Kumar Purushothaman
Nov 16 '17 at 21:21
add a comment |
You can add a simple forEach function to all objects, so you can automatically loop through any object:
Object.defineProperty(Object.prototype, 'forEach', {
value: function (func) {
for (var key in this) {
if (!this.hasOwnProperty(key)) {
// skip loop if the property is from prototype
continue;
}
var value = this[key];
func(key, value);
}
},
enumerable: false
});
For those people who don't like the "for ... in"-method:
Object.defineProperty(Object.prototype, 'forEach', {
value: function (func) {
var arr = Object.keys(this);
for (var i = 0; i < arr.length; i++) {
var key = arr[i];
func(key, this[key]);
}
},
enumerable: false
});
Now, you can simple call:
p.forEach (function(key, value){
console.log ("Key: " + key);
console.log ("Value: " + value);
});
If you don't want to get conflicts with other forEach-Methods you can name it with your unique name.
3
Modifying the prototypes of built in objects (likeObject
) is generally considered an anti pattern because it can easily cause conflicts with other code. So wound not recommend doing it this way.
– Moritz
Jan 6 '17 at 13:06
add a comment |
Only JavaScript code without dependencies:
var p = {"p1": "value1", "p2": "value2", "p3": "value3"};
keys = Object.keys(p); // ["p1", "p2", "p3"]
for(i = 0; i < keys.length; i++){
console.log(keys[i] + "=" + p[keys[i]]); // p1=value1, p2=value2, p3=value3
}
add a comment |
Loops can be pretty interesting when using pure JavaScript. It seems that only ECMA6 (New 2015 JavaScript specification) got the loops under control. Unfortunately as I'm writing this, both Browsers and popular Integrated development environment (IDE) are still struggling to support completely the new bells and whistles.
At a glance here is what a JavaScript object loop look like before ECMA6:
for (var key in object) {
if (p.hasOwnProperty(key)) {
var value = object[key];
console.log(key); // This is the key;
console.log(value); // This is the value;
}
}
Also, I know this is out of scope with this question but in 2011, ECMAScript 5.1 added the forEach
method for Arrays only which basically created a new improved way to loop through arrays while still leaving non iterable objects with the old verbose and confusing for
loop. But the odd part is that this new forEach
method does not support break
which led to all sorts of other problems.
Basically in 2011, there is not a real solid way to loop in JavaScript other than what many popular libraries (jQuery, Underscore, etc.) decided to re-implement.
As of 2015, we now have a better out of the box way to loop (and break) any object type (including Arrays and Strings). Here is what a loop in JavaScript will eventually look like when the recommendation becomes mainstream:
for (let [key, value] of Object.entries(object)) {
console.log(key); // This is the key;
console.log(value); // This is the value;
}
Note that most browsers won't support the code above as of June 18th 2016. Even in Chrome you need to enable this special flag for it to work: chrome://flags/#enable-javascript-harmony
Until this becomes the new standard, the old method can still be used but there are also alternatives in popular libraries or even lightweight alternatives for those who aren't using any of these libraries.
Could you provide a fiddle of this working? Here is my attempt. jsfiddle.net/abalter/sceeb211
– abalter
Jun 18 '16 at 6:24
@abalter Sorry I realised I had a typo in my code. I fixed it and updated your JsFiddle here: jsfiddle.net/sceeb211/2
– Nicolas Bouvrette
Jun 18 '16 at 12:56
I'm in chrome and gettingUncaught TypeError: Object.entries is not a function
. Is it not implemented in chrome yet?
– abalter
Jun 18 '16 at 16:07
@abalter It is. Make sure you have Chrome version 51 and that you have enabled the flag as explained in my edit and Jsfiddle comments. You can check the details here: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
– Nicolas Bouvrette
Jun 18 '16 at 16:39
Sorry I missed that about the flag. I see it's not a fully implemented feature yet.
– abalter
Jun 19 '16 at 5:39
|
show 3 more comments
I would do this rather than checking obj.hasOwnerProperty
within every for ... in
loop.
var obj = {a : 1};
for(var key in obj){
//obj.hasOwnProperty(key) is not needed.
console.log(key);
}
//then check if anybody has messed the native object. Put this code at the end of the page.
for(var key in Object){
throw new Error("Please don't extend the native object");
}
add a comment |
If you want to iterate over non-enumerable properties as well, you can use Object.getOwnPropertyNames(obj)
to return an array of all properties (enumerable or not) found directly upon a given object.
var obj = Object.create({}, {
// non-enumerable property
getFoo: {
value: function() { return this.foo; },
enumerable: false
}
});
obj.foo = 1; // enumerable property
Object.getOwnPropertyNames(obj).forEach(function (name) {
document.write(name + ': ' + obj[name] + '<br/>');
});
2
This is fantastic, thank you for posting this answer. I needed to introspect anError
object and couldn't get at the properties in a loop or a_.forIn(err)
call. UsingObject.getOwnPropertyNames(err)
allowed me to access all the parts of theError
that I couldn't get at before. Thanks!
– Pierce
Mar 11 '16 at 19:49
add a comment |
If anybody needs to loop through arrayObjects with condition:
var arrayObjects = [{"building":"A", "status":"good"},{"building":"B","status":"horrible"}];
for (var i=0; i< arrayObjects.length; i++) {
console.log(arrayObjects[i]);
for(key in arrayObjects[i]) {
if (key == "status" && arrayObjects[i][key] == "good") {
console.log(key + "->" + arrayObjects[i][key]);
}else{
console.log("nothing found");
}
}
}
add a comment |
Considering ES6 I'd like to add my own spoon of sugar and provide one more approach to iterate over object's properties.
Since plain JS object isn't iterable just out of box, we aren't able to use for..of
loop for iterating over its content. But no one can stop us to make it iterable.
Let's we have book
object.
let book = {
title: "Amazing book",
author: "Me",
pages: 3
}
book[Symbol.iterator] = function(){
let properties = Object.keys(this); // returns an array with property names
let counter = 0;
let isDone = false;
let next = () => {
if(counter >= properties.length){
isDone = true;
}
return { done: isDone, value: this[properties[counter++]] }
}
return { next };
}
Since we've made it we can use it this way:
for(let pValue of book){
console.log(pValue);
}
------------------------
Amazing book
Me
3
Or if you know the power of ES6 generators, so you certainly can make the code above much shorter.
book[Symbol.iterator] = function *(){
let properties = Object.keys(this);
for (let p of properties){
yield this[p];
}
}
Sure, you can apply such behavior for all objects with making Object
iterable on prototype
level.
Object.prototype[Symbol.iterator] = function() {...}
Also, objects that comply with the iterable protocol can be used with the new ES2015 feature spread operator thus we can read object property values as an array.
let pValues = [...book];
console.log(pValues);
-------------------------
["Amazing book", "Me", 3]
Or you can use destructuring assignment:
let [title, , pages] = book; // notice that we can just skip unnecessary values
console.log(title);
console.log(pages);
------------------
Amazing book
3
You can check out JSFiddle with all code I've provided above.
I found the code will generate the values but without keys. Is it possible to iterate the values with keys?
– Pika
Sep 8 '16 at 3:34
Yes, you can. Just return "yield [key, obj[key]];" from your generator function and then use it like the following "for(let [ key, value ] of {}) { }"
– Artyom Pranovich
Sep 8 '16 at 13:33
add a comment |
In latest ES script, you can do something like this:
Object.entries(p);
add a comment |
var p =[{"username":"ordermanageadmin","user_id":"2","resource_id":"Magento_Sales::actions"},
{"username":"ordermanageadmin_1","user_id":"3","resource_id":"Magento_Sales::actions"}]
for(var value in p) {
for (var key in value) {
if (p.hasOwnProperty(key)) {
console.log(key + " -> " + p[key]);
}
}
}
json = [{"key1":"value1","key2":"value2"},{"key1":"value3","key2":"value4"}] for (var i = 0; i < json.length; i++) { for (var key in json[i]) { if (json[i].hasOwnProperty(key)) { console.log(key + " -> " + json[i][key]); } } }
– Marek Bernád
Oct 14 '18 at 12:27
add a comment |
In ES6 we have well-known symbols to expose some previously internal methods, you can use it to define how iterators work for this object:
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3",
*[Symbol.iterator]() {
yield *Object.keys(this);
}
};
[...p] //["p1", "p2", "p3"]
this will give the same result as using for...in es6 loop.
for(var key in p) {
console.log(key);
}
But its important to know the capabilities you now have using es6!
add a comment |
An object becomes an iterator when it implements the .next() method
const james = {
name: 'James',
height: `5'10"`,
weight: 185,
[Symbol.iterator]() {
let properties =
for (let key of Object.keys(james)){
properties.push(key);
}
index = 0;
return {
next: () => {
let key = properties[index];
let value = this[key];
let done = index >= properties.length - 1 ;
index++;
return { key, value, done };
}
};
}
};
const iterator = james[Symbol.iterator]();
console.log(iterator.next().value); // 'James'
console.log(iterator.next().value); // `5'10`
console.log(iterator.next().value); // 185
add a comment |
since ES06 you can get the values of an object as array with
let arrValues = Object.values( yourObject) ;
it return the an array of the object values and it not extract values from Prototype!!
MDN DOCS Object.values()
and for keys ( allready answerd before me here )
let arrKeys = Object.keys(yourObject);
The answers asks for a solution that returns both keys and values.
– Sean Lindo
Aug 21 '18 at 19:03
pepole allready answer for that. i add it now for you
– yehonatan yehezkel
Aug 22 '18 at 15:42
add a comment |
If you want to iterate only over properties use one of the answers above, however if you want to iterate over everything including functions, then you might want to use Object.getOwnPropertyNames(obj)
for (let o of Object.getOwnPropertyNames(Math)) {
console.log(o);
}
I sometimes use this to fast test all functions on objects with simple inputs and outputs.
add a comment |
Object.entries()
function:
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
for (var i in Object.entries(p)){
var key = Object.entries(p)[i][0];
var value = Object.entries(p)[i][1];
console.log('key['+i+']='+key+' '+'value['+i+']='+value);
}
please don't remove the snippet if you edit my entry
– nrb
Oct 29 '18 at 19:22
add a comment |
1 2
next
protected by VisioN Feb 27 '13 at 8:52
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?
35 Answers
35
active
oldest
votes
35 Answers
35
active
oldest
votes
active
oldest
votes
active
oldest
votes
1 2
next
You can use the for-in
loop as shown by others. However, you also have to make sure that the key you get is an actual property of an object, and doesn't come from the prototype.
Here is the snippet:
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
for (var key in p) {
if (p.hasOwnProperty(key)) {
console.log(key + " -> " + p[key]);
}
}
27
Would propose that you change the alert line just for clarity toalert(key + " -> " + JSON.stringify(p[key]));
– Steve Midgley
Aug 18 '11 at 22:03
69
Can you explain the need for hasOwnProperty? What you mean by prototype?
– kamaci
Aug 22 '11 at 12:46
299
In javascript, every object has a bunch of built-in key-value pairs that have meta-information. When you loop through all the key-value pairs for an object you're looping through them too. hasOwnPropery() filters these out.
– danieltalsky
Jan 27 '12 at 15:56
51
Actually, For...in is not deprecated. For each...in is. But I really like the term archaeologists...I'm going to have to start using that.
– Ben Y
Feb 27 '14 at 16:08
11
each object in javascript (actually a key-value pair) has a property called__proto__
orprototype
. This property has a reference to its parent object. An object automatically inherits property from its parent. This is the reason of usinghasOwnProperty
, which signifies that we're interested in objects own property and not its parent ones.
– Zubair Alam
Aug 29 '14 at 19:01
|
show 17 more comments
You can use the for-in
loop as shown by others. However, you also have to make sure that the key you get is an actual property of an object, and doesn't come from the prototype.
Here is the snippet:
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
for (var key in p) {
if (p.hasOwnProperty(key)) {
console.log(key + " -> " + p[key]);
}
}
27
Would propose that you change the alert line just for clarity toalert(key + " -> " + JSON.stringify(p[key]));
– Steve Midgley
Aug 18 '11 at 22:03
69
Can you explain the need for hasOwnProperty? What you mean by prototype?
– kamaci
Aug 22 '11 at 12:46
299
In javascript, every object has a bunch of built-in key-value pairs that have meta-information. When you loop through all the key-value pairs for an object you're looping through them too. hasOwnPropery() filters these out.
– danieltalsky
Jan 27 '12 at 15:56
51
Actually, For...in is not deprecated. For each...in is. But I really like the term archaeologists...I'm going to have to start using that.
– Ben Y
Feb 27 '14 at 16:08
11
each object in javascript (actually a key-value pair) has a property called__proto__
orprototype
. This property has a reference to its parent object. An object automatically inherits property from its parent. This is the reason of usinghasOwnProperty
, which signifies that we're interested in objects own property and not its parent ones.
– Zubair Alam
Aug 29 '14 at 19:01
|
show 17 more comments
You can use the for-in
loop as shown by others. However, you also have to make sure that the key you get is an actual property of an object, and doesn't come from the prototype.
Here is the snippet:
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
for (var key in p) {
if (p.hasOwnProperty(key)) {
console.log(key + " -> " + p[key]);
}
}
You can use the for-in
loop as shown by others. However, you also have to make sure that the key you get is an actual property of an object, and doesn't come from the prototype.
Here is the snippet:
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
for (var key in p) {
if (p.hasOwnProperty(key)) {
console.log(key + " -> " + p[key]);
}
}
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
for (var key in p) {
if (p.hasOwnProperty(key)) {
console.log(key + " -> " + p[key]);
}
}
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
for (var key in p) {
if (p.hasOwnProperty(key)) {
console.log(key + " -> " + p[key]);
}
}
edited Oct 18 '17 at 9:42
1stthomas
6442918
6442918
answered Mar 26 '09 at 6:12
leviklevik
73.2k236689
73.2k236689
27
Would propose that you change the alert line just for clarity toalert(key + " -> " + JSON.stringify(p[key]));
– Steve Midgley
Aug 18 '11 at 22:03
69
Can you explain the need for hasOwnProperty? What you mean by prototype?
– kamaci
Aug 22 '11 at 12:46
299
In javascript, every object has a bunch of built-in key-value pairs that have meta-information. When you loop through all the key-value pairs for an object you're looping through them too. hasOwnPropery() filters these out.
– danieltalsky
Jan 27 '12 at 15:56
51
Actually, For...in is not deprecated. For each...in is. But I really like the term archaeologists...I'm going to have to start using that.
– Ben Y
Feb 27 '14 at 16:08
11
each object in javascript (actually a key-value pair) has a property called__proto__
orprototype
. This property has a reference to its parent object. An object automatically inherits property from its parent. This is the reason of usinghasOwnProperty
, which signifies that we're interested in objects own property and not its parent ones.
– Zubair Alam
Aug 29 '14 at 19:01
|
show 17 more comments
27
Would propose that you change the alert line just for clarity toalert(key + " -> " + JSON.stringify(p[key]));
– Steve Midgley
Aug 18 '11 at 22:03
69
Can you explain the need for hasOwnProperty? What you mean by prototype?
– kamaci
Aug 22 '11 at 12:46
299
In javascript, every object has a bunch of built-in key-value pairs that have meta-information. When you loop through all the key-value pairs for an object you're looping through them too. hasOwnPropery() filters these out.
– danieltalsky
Jan 27 '12 at 15:56
51
Actually, For...in is not deprecated. For each...in is. But I really like the term archaeologists...I'm going to have to start using that.
– Ben Y
Feb 27 '14 at 16:08
11
each object in javascript (actually a key-value pair) has a property called__proto__
orprototype
. This property has a reference to its parent object. An object automatically inherits property from its parent. This is the reason of usinghasOwnProperty
, which signifies that we're interested in objects own property and not its parent ones.
– Zubair Alam
Aug 29 '14 at 19:01
27
27
Would propose that you change the alert line just for clarity to
alert(key + " -> " + JSON.stringify(p[key]));
– Steve Midgley
Aug 18 '11 at 22:03
Would propose that you change the alert line just for clarity to
alert(key + " -> " + JSON.stringify(p[key]));
– Steve Midgley
Aug 18 '11 at 22:03
69
69
Can you explain the need for hasOwnProperty? What you mean by prototype?
– kamaci
Aug 22 '11 at 12:46
Can you explain the need for hasOwnProperty? What you mean by prototype?
– kamaci
Aug 22 '11 at 12:46
299
299
In javascript, every object has a bunch of built-in key-value pairs that have meta-information. When you loop through all the key-value pairs for an object you're looping through them too. hasOwnPropery() filters these out.
– danieltalsky
Jan 27 '12 at 15:56
In javascript, every object has a bunch of built-in key-value pairs that have meta-information. When you loop through all the key-value pairs for an object you're looping through them too. hasOwnPropery() filters these out.
– danieltalsky
Jan 27 '12 at 15:56
51
51
Actually, For...in is not deprecated. For each...in is. But I really like the term archaeologists...I'm going to have to start using that.
– Ben Y
Feb 27 '14 at 16:08
Actually, For...in is not deprecated. For each...in is. But I really like the term archaeologists...I'm going to have to start using that.
– Ben Y
Feb 27 '14 at 16:08
11
11
each object in javascript (actually a key-value pair) has a property called
__proto__
or prototype
. This property has a reference to its parent object. An object automatically inherits property from its parent. This is the reason of using hasOwnProperty
, which signifies that we're interested in objects own property and not its parent ones.– Zubair Alam
Aug 29 '14 at 19:01
each object in javascript (actually a key-value pair) has a property called
__proto__
or prototype
. This property has a reference to its parent object. An object automatically inherits property from its parent. This is the reason of using hasOwnProperty
, which signifies that we're interested in objects own property and not its parent ones.– Zubair Alam
Aug 29 '14 at 19:01
|
show 17 more comments
Under ECMAScript 5, you can combine Object.keys()
and Array.prototype.forEach()
:
var obj = { first: "John", last: "Doe" };
Object.keys(obj).forEach(function(key) {
console.log(key, obj[key]);
});
ECMAScript 6 adds for...of
:
for (const key of Object.keys(obj)) {
console.log(key, obj[key]);
}
ECMAScript 8 adds Object.entries()
which avoids having to look up each value in the original object:
Object.entries(obj).forEach(
([key, value]) => console.log(key, value)
);
Both Object.keys()
and Object.entries()
iterate properties in the same order as a for...in
loop but ignore the prototype chain. Only the object's own enumerable properties are iterated.
18
Why didn't the standard provideObject.forEach(obj, function (value, key) {...})
? :( Certainlyobj.forEach(function...)
would be shorter and complementArray.prototype.forEach
, but that would risk having objects define their ownforEach
property. I supposeObject.keys
guards against the callback modifying the object's keys.
– David Harkness
Jun 23 '14 at 20:36
6
Object.forEach = function (obj, callback) { Object.keys(obj).forEach(function (key) { callback(obj[key], key); }); }
– David Harkness
Jun 23 '14 at 20:41
5
@DavidHarkness There is Object.entries in ES2017. There you can do the following:Object.entries(obj).map/forEach(([key, value]) => console.log(key, value))
([key, value] is array destructuring, to access both items directly. And you have to wrap the parameters in additional parens.)
– Andreas Linnert
Jul 14 '16 at 12:50
how do I getindex
of the key in json? Or if required i should use a separate counter?
– Saravanabalagi Ramachandran
Jan 22 '17 at 15:42
2
for...of
is ES6 standard, not ES2016.
– Rax Weber
Sep 6 '17 at 7:45
|
show 5 more comments
Under ECMAScript 5, you can combine Object.keys()
and Array.prototype.forEach()
:
var obj = { first: "John", last: "Doe" };
Object.keys(obj).forEach(function(key) {
console.log(key, obj[key]);
});
ECMAScript 6 adds for...of
:
for (const key of Object.keys(obj)) {
console.log(key, obj[key]);
}
ECMAScript 8 adds Object.entries()
which avoids having to look up each value in the original object:
Object.entries(obj).forEach(
([key, value]) => console.log(key, value)
);
Both Object.keys()
and Object.entries()
iterate properties in the same order as a for...in
loop but ignore the prototype chain. Only the object's own enumerable properties are iterated.
18
Why didn't the standard provideObject.forEach(obj, function (value, key) {...})
? :( Certainlyobj.forEach(function...)
would be shorter and complementArray.prototype.forEach
, but that would risk having objects define their ownforEach
property. I supposeObject.keys
guards against the callback modifying the object's keys.
– David Harkness
Jun 23 '14 at 20:36
6
Object.forEach = function (obj, callback) { Object.keys(obj).forEach(function (key) { callback(obj[key], key); }); }
– David Harkness
Jun 23 '14 at 20:41
5
@DavidHarkness There is Object.entries in ES2017. There you can do the following:Object.entries(obj).map/forEach(([key, value]) => console.log(key, value))
([key, value] is array destructuring, to access both items directly. And you have to wrap the parameters in additional parens.)
– Andreas Linnert
Jul 14 '16 at 12:50
how do I getindex
of the key in json? Or if required i should use a separate counter?
– Saravanabalagi Ramachandran
Jan 22 '17 at 15:42
2
for...of
is ES6 standard, not ES2016.
– Rax Weber
Sep 6 '17 at 7:45
|
show 5 more comments
Under ECMAScript 5, you can combine Object.keys()
and Array.prototype.forEach()
:
var obj = { first: "John", last: "Doe" };
Object.keys(obj).forEach(function(key) {
console.log(key, obj[key]);
});
ECMAScript 6 adds for...of
:
for (const key of Object.keys(obj)) {
console.log(key, obj[key]);
}
ECMAScript 8 adds Object.entries()
which avoids having to look up each value in the original object:
Object.entries(obj).forEach(
([key, value]) => console.log(key, value)
);
Both Object.keys()
and Object.entries()
iterate properties in the same order as a for...in
loop but ignore the prototype chain. Only the object's own enumerable properties are iterated.
Under ECMAScript 5, you can combine Object.keys()
and Array.prototype.forEach()
:
var obj = { first: "John", last: "Doe" };
Object.keys(obj).forEach(function(key) {
console.log(key, obj[key]);
});
ECMAScript 6 adds for...of
:
for (const key of Object.keys(obj)) {
console.log(key, obj[key]);
}
ECMAScript 8 adds Object.entries()
which avoids having to look up each value in the original object:
Object.entries(obj).forEach(
([key, value]) => console.log(key, value)
);
Both Object.keys()
and Object.entries()
iterate properties in the same order as a for...in
loop but ignore the prototype chain. Only the object's own enumerable properties are iterated.
edited Nov 19 '18 at 3:54
Ricky Boyce
8131020
8131020
answered Apr 20 '11 at 21:59
Axel RauschmayerAxel Rauschmayer
16.6k31613
16.6k31613
18
Why didn't the standard provideObject.forEach(obj, function (value, key) {...})
? :( Certainlyobj.forEach(function...)
would be shorter and complementArray.prototype.forEach
, but that would risk having objects define their ownforEach
property. I supposeObject.keys
guards against the callback modifying the object's keys.
– David Harkness
Jun 23 '14 at 20:36
6
Object.forEach = function (obj, callback) { Object.keys(obj).forEach(function (key) { callback(obj[key], key); }); }
– David Harkness
Jun 23 '14 at 20:41
5
@DavidHarkness There is Object.entries in ES2017. There you can do the following:Object.entries(obj).map/forEach(([key, value]) => console.log(key, value))
([key, value] is array destructuring, to access both items directly. And you have to wrap the parameters in additional parens.)
– Andreas Linnert
Jul 14 '16 at 12:50
how do I getindex
of the key in json? Or if required i should use a separate counter?
– Saravanabalagi Ramachandran
Jan 22 '17 at 15:42
2
for...of
is ES6 standard, not ES2016.
– Rax Weber
Sep 6 '17 at 7:45
|
show 5 more comments
18
Why didn't the standard provideObject.forEach(obj, function (value, key) {...})
? :( Certainlyobj.forEach(function...)
would be shorter and complementArray.prototype.forEach
, but that would risk having objects define their ownforEach
property. I supposeObject.keys
guards against the callback modifying the object's keys.
– David Harkness
Jun 23 '14 at 20:36
6
Object.forEach = function (obj, callback) { Object.keys(obj).forEach(function (key) { callback(obj[key], key); }); }
– David Harkness
Jun 23 '14 at 20:41
5
@DavidHarkness There is Object.entries in ES2017. There you can do the following:Object.entries(obj).map/forEach(([key, value]) => console.log(key, value))
([key, value] is array destructuring, to access both items directly. And you have to wrap the parameters in additional parens.)
– Andreas Linnert
Jul 14 '16 at 12:50
how do I getindex
of the key in json? Or if required i should use a separate counter?
– Saravanabalagi Ramachandran
Jan 22 '17 at 15:42
2
for...of
is ES6 standard, not ES2016.
– Rax Weber
Sep 6 '17 at 7:45
18
18
Why didn't the standard provide
Object.forEach(obj, function (value, key) {...})
? :( Certainly obj.forEach(function...)
would be shorter and complement Array.prototype.forEach
, but that would risk having objects define their own forEach
property. I suppose Object.keys
guards against the callback modifying the object's keys.– David Harkness
Jun 23 '14 at 20:36
Why didn't the standard provide
Object.forEach(obj, function (value, key) {...})
? :( Certainly obj.forEach(function...)
would be shorter and complement Array.prototype.forEach
, but that would risk having objects define their own forEach
property. I suppose Object.keys
guards against the callback modifying the object's keys.– David Harkness
Jun 23 '14 at 20:36
6
6
Object.forEach = function (obj, callback) { Object.keys(obj).forEach(function (key) { callback(obj[key], key); }); }
– David Harkness
Jun 23 '14 at 20:41
Object.forEach = function (obj, callback) { Object.keys(obj).forEach(function (key) { callback(obj[key], key); }); }
– David Harkness
Jun 23 '14 at 20:41
5
5
@DavidHarkness There is Object.entries in ES2017. There you can do the following:
Object.entries(obj).map/forEach(([key, value]) => console.log(key, value))
([key, value] is array destructuring, to access both items directly. And you have to wrap the parameters in additional parens.)– Andreas Linnert
Jul 14 '16 at 12:50
@DavidHarkness There is Object.entries in ES2017. There you can do the following:
Object.entries(obj).map/forEach(([key, value]) => console.log(key, value))
([key, value] is array destructuring, to access both items directly. And you have to wrap the parameters in additional parens.)– Andreas Linnert
Jul 14 '16 at 12:50
how do I get
index
of the key in json? Or if required i should use a separate counter?– Saravanabalagi Ramachandran
Jan 22 '17 at 15:42
how do I get
index
of the key in json? Or if required i should use a separate counter?– Saravanabalagi Ramachandran
Jan 22 '17 at 15:42
2
2
for...of
is ES6 standard, not ES2016.– Rax Weber
Sep 6 '17 at 7:45
for...of
is ES6 standard, not ES2016.– Rax Weber
Sep 6 '17 at 7:45
|
show 5 more comments
You have to use the for-in loop
But be very careful when using this kind of loop, because this will loop all the properties along the prototype chain.
Therefore, when using for-in loops, always make use of the hasOwnProperty
method to determine if the current property in iteration is really a property of the object you're checking on:
for (var prop in p) {
if (!p.hasOwnProperty(prop)) {
//The current property is not a direct property of p
continue;
}
//Do your logic with the property here
}
30
This is better than levik's solution because it allows the main logic to be only one nested loop in rather than two; making for easier to read code. Although I'd loose the the brackets around the continue; they are superfluous.
– SystemicPlural
Apr 6 '11 at 9:55
50
I would not remove the{ }
personally because anif
without them makes it a little unclear what is part of theif
and what is not. But I guess that's just a matter of opinion :)
– pimvdb
Aug 5 '11 at 12:01
31
Yes, I prefer keeping the{ }
mainly to avoid confusion if one later on needs to add something to theif
scope.
– Andreas Grech
Aug 5 '11 at 12:21
8
Reading my previous comment, I realized that I didn't use the correct terms, because I said "if scope"; but keep in mind that JavaScript only has function scope. So what I actually meant was "if block".
– Andreas Grech
Nov 11 '11 at 11:08
1
eomeroff, if you're really concerned about that, you could always do something like:Object.prototype.hasOwnProperty.call(p, prop)
However, this too can't protect against manipulations to Object.prototype...
– jordancpaul
Oct 15 '13 at 7:37
|
show 3 more comments
You have to use the for-in loop
But be very careful when using this kind of loop, because this will loop all the properties along the prototype chain.
Therefore, when using for-in loops, always make use of the hasOwnProperty
method to determine if the current property in iteration is really a property of the object you're checking on:
for (var prop in p) {
if (!p.hasOwnProperty(prop)) {
//The current property is not a direct property of p
continue;
}
//Do your logic with the property here
}
30
This is better than levik's solution because it allows the main logic to be only one nested loop in rather than two; making for easier to read code. Although I'd loose the the brackets around the continue; they are superfluous.
– SystemicPlural
Apr 6 '11 at 9:55
50
I would not remove the{ }
personally because anif
without them makes it a little unclear what is part of theif
and what is not. But I guess that's just a matter of opinion :)
– pimvdb
Aug 5 '11 at 12:01
31
Yes, I prefer keeping the{ }
mainly to avoid confusion if one later on needs to add something to theif
scope.
– Andreas Grech
Aug 5 '11 at 12:21
8
Reading my previous comment, I realized that I didn't use the correct terms, because I said "if scope"; but keep in mind that JavaScript only has function scope. So what I actually meant was "if block".
– Andreas Grech
Nov 11 '11 at 11:08
1
eomeroff, if you're really concerned about that, you could always do something like:Object.prototype.hasOwnProperty.call(p, prop)
However, this too can't protect against manipulations to Object.prototype...
– jordancpaul
Oct 15 '13 at 7:37
|
show 3 more comments
You have to use the for-in loop
But be very careful when using this kind of loop, because this will loop all the properties along the prototype chain.
Therefore, when using for-in loops, always make use of the hasOwnProperty
method to determine if the current property in iteration is really a property of the object you're checking on:
for (var prop in p) {
if (!p.hasOwnProperty(prop)) {
//The current property is not a direct property of p
continue;
}
//Do your logic with the property here
}
You have to use the for-in loop
But be very careful when using this kind of loop, because this will loop all the properties along the prototype chain.
Therefore, when using for-in loops, always make use of the hasOwnProperty
method to determine if the current property in iteration is really a property of the object you're checking on:
for (var prop in p) {
if (!p.hasOwnProperty(prop)) {
//The current property is not a direct property of p
continue;
}
//Do your logic with the property here
}
edited Feb 24 '16 at 10:51


Vitim.us
10.1k96485
10.1k96485
answered Mar 26 '09 at 6:12
Andreas GrechAndreas Grech
63.1k92272348
63.1k92272348
30
This is better than levik's solution because it allows the main logic to be only one nested loop in rather than two; making for easier to read code. Although I'd loose the the brackets around the continue; they are superfluous.
– SystemicPlural
Apr 6 '11 at 9:55
50
I would not remove the{ }
personally because anif
without them makes it a little unclear what is part of theif
and what is not. But I guess that's just a matter of opinion :)
– pimvdb
Aug 5 '11 at 12:01
31
Yes, I prefer keeping the{ }
mainly to avoid confusion if one later on needs to add something to theif
scope.
– Andreas Grech
Aug 5 '11 at 12:21
8
Reading my previous comment, I realized that I didn't use the correct terms, because I said "if scope"; but keep in mind that JavaScript only has function scope. So what I actually meant was "if block".
– Andreas Grech
Nov 11 '11 at 11:08
1
eomeroff, if you're really concerned about that, you could always do something like:Object.prototype.hasOwnProperty.call(p, prop)
However, this too can't protect against manipulations to Object.prototype...
– jordancpaul
Oct 15 '13 at 7:37
|
show 3 more comments
30
This is better than levik's solution because it allows the main logic to be only one nested loop in rather than two; making for easier to read code. Although I'd loose the the brackets around the continue; they are superfluous.
– SystemicPlural
Apr 6 '11 at 9:55
50
I would not remove the{ }
personally because anif
without them makes it a little unclear what is part of theif
and what is not. But I guess that's just a matter of opinion :)
– pimvdb
Aug 5 '11 at 12:01
31
Yes, I prefer keeping the{ }
mainly to avoid confusion if one later on needs to add something to theif
scope.
– Andreas Grech
Aug 5 '11 at 12:21
8
Reading my previous comment, I realized that I didn't use the correct terms, because I said "if scope"; but keep in mind that JavaScript only has function scope. So what I actually meant was "if block".
– Andreas Grech
Nov 11 '11 at 11:08
1
eomeroff, if you're really concerned about that, you could always do something like:Object.prototype.hasOwnProperty.call(p, prop)
However, this too can't protect against manipulations to Object.prototype...
– jordancpaul
Oct 15 '13 at 7:37
30
30
This is better than levik's solution because it allows the main logic to be only one nested loop in rather than two; making for easier to read code. Although I'd loose the the brackets around the continue; they are superfluous.
– SystemicPlural
Apr 6 '11 at 9:55
This is better than levik's solution because it allows the main logic to be only one nested loop in rather than two; making for easier to read code. Although I'd loose the the brackets around the continue; they are superfluous.
– SystemicPlural
Apr 6 '11 at 9:55
50
50
I would not remove the
{ }
personally because an if
without them makes it a little unclear what is part of the if
and what is not. But I guess that's just a matter of opinion :)– pimvdb
Aug 5 '11 at 12:01
I would not remove the
{ }
personally because an if
without them makes it a little unclear what is part of the if
and what is not. But I guess that's just a matter of opinion :)– pimvdb
Aug 5 '11 at 12:01
31
31
Yes, I prefer keeping the
{ }
mainly to avoid confusion if one later on needs to add something to the if
scope.– Andreas Grech
Aug 5 '11 at 12:21
Yes, I prefer keeping the
{ }
mainly to avoid confusion if one later on needs to add something to the if
scope.– Andreas Grech
Aug 5 '11 at 12:21
8
8
Reading my previous comment, I realized that I didn't use the correct terms, because I said "if scope"; but keep in mind that JavaScript only has function scope. So what I actually meant was "if block".
– Andreas Grech
Nov 11 '11 at 11:08
Reading my previous comment, I realized that I didn't use the correct terms, because I said "if scope"; but keep in mind that JavaScript only has function scope. So what I actually meant was "if block".
– Andreas Grech
Nov 11 '11 at 11:08
1
1
eomeroff, if you're really concerned about that, you could always do something like:
Object.prototype.hasOwnProperty.call(p, prop)
However, this too can't protect against manipulations to Object.prototype...– jordancpaul
Oct 15 '13 at 7:37
eomeroff, if you're really concerned about that, you could always do something like:
Object.prototype.hasOwnProperty.call(p, prop)
However, this too can't protect against manipulations to Object.prototype...– jordancpaul
Oct 15 '13 at 7:37
|
show 3 more comments
The question won't be complete if we don't mention about alternative methods for looping through objects.
Nowadays many well known JavaScript libraries provide their own methods for iterating over collections, i.e. over arrays, objects, and array-like objects. These methods are convenient to use and are entirely compatible with any browser.
If you work with jQuery, you may use
jQuery.each()
method. It can be used to seamlessly iterate over both objects and arrays:
$.each(obj, function(key, value) {
console.log(key, value);
});
In Underscore.js you can find method
_.each()
, which iterates over a list of elements, yielding each in turn to a supplied function (pay attention to the order of arguments in iteratee function!):
_.each(obj, function(value, key) {
console.log(key, value);
});
Lo-Dash provides several methods for iterating over object properties. Basic
_.forEach()
(or it's alias_.each()
) is useful for looping through both objects and arrays, however (!) objects withlength
property are treated like arrays, and to avoid this behavior it is suggested to use_.forIn()
and_.forOwn()
methods (these also havevalue
argument coming first):
_.forIn(obj, function(value, key) {
console.log(key, value);
});
_.forIn()
iterates over own and inherited enumerable properties of an object, while_.forOwn()
iterates only over own properties of an object (basically checking againsthasOwnProperty
function). For simple objects and object literals any of these methods will work fine.
Generally all described methods have the same behaviour with any supplied objects. Besides using native for..in
loop will usually be faster than any abstraction, such as jQuery.each()
, these methods are considerably easier to use, require less coding and provide better error handling.
4
To get to the value: $.each(obj, function (key, value) { console.log(value.title); });
– Ravi Ram
Jun 8 '13 at 14:41
2
Just funny how underscore and jquery changed parameters :)
– ppasler
Sep 8 '17 at 7:24
add a comment |
The question won't be complete if we don't mention about alternative methods for looping through objects.
Nowadays many well known JavaScript libraries provide their own methods for iterating over collections, i.e. over arrays, objects, and array-like objects. These methods are convenient to use and are entirely compatible with any browser.
If you work with jQuery, you may use
jQuery.each()
method. It can be used to seamlessly iterate over both objects and arrays:
$.each(obj, function(key, value) {
console.log(key, value);
});
In Underscore.js you can find method
_.each()
, which iterates over a list of elements, yielding each in turn to a supplied function (pay attention to the order of arguments in iteratee function!):
_.each(obj, function(value, key) {
console.log(key, value);
});
Lo-Dash provides several methods for iterating over object properties. Basic
_.forEach()
(or it's alias_.each()
) is useful for looping through both objects and arrays, however (!) objects withlength
property are treated like arrays, and to avoid this behavior it is suggested to use_.forIn()
and_.forOwn()
methods (these also havevalue
argument coming first):
_.forIn(obj, function(value, key) {
console.log(key, value);
});
_.forIn()
iterates over own and inherited enumerable properties of an object, while_.forOwn()
iterates only over own properties of an object (basically checking againsthasOwnProperty
function). For simple objects and object literals any of these methods will work fine.
Generally all described methods have the same behaviour with any supplied objects. Besides using native for..in
loop will usually be faster than any abstraction, such as jQuery.each()
, these methods are considerably easier to use, require less coding and provide better error handling.
4
To get to the value: $.each(obj, function (key, value) { console.log(value.title); });
– Ravi Ram
Jun 8 '13 at 14:41
2
Just funny how underscore and jquery changed parameters :)
– ppasler
Sep 8 '17 at 7:24
add a comment |
The question won't be complete if we don't mention about alternative methods for looping through objects.
Nowadays many well known JavaScript libraries provide their own methods for iterating over collections, i.e. over arrays, objects, and array-like objects. These methods are convenient to use and are entirely compatible with any browser.
If you work with jQuery, you may use
jQuery.each()
method. It can be used to seamlessly iterate over both objects and arrays:
$.each(obj, function(key, value) {
console.log(key, value);
});
In Underscore.js you can find method
_.each()
, which iterates over a list of elements, yielding each in turn to a supplied function (pay attention to the order of arguments in iteratee function!):
_.each(obj, function(value, key) {
console.log(key, value);
});
Lo-Dash provides several methods for iterating over object properties. Basic
_.forEach()
(or it's alias_.each()
) is useful for looping through both objects and arrays, however (!) objects withlength
property are treated like arrays, and to avoid this behavior it is suggested to use_.forIn()
and_.forOwn()
methods (these also havevalue
argument coming first):
_.forIn(obj, function(value, key) {
console.log(key, value);
});
_.forIn()
iterates over own and inherited enumerable properties of an object, while_.forOwn()
iterates only over own properties of an object (basically checking againsthasOwnProperty
function). For simple objects and object literals any of these methods will work fine.
Generally all described methods have the same behaviour with any supplied objects. Besides using native for..in
loop will usually be faster than any abstraction, such as jQuery.each()
, these methods are considerably easier to use, require less coding and provide better error handling.
The question won't be complete if we don't mention about alternative methods for looping through objects.
Nowadays many well known JavaScript libraries provide their own methods for iterating over collections, i.e. over arrays, objects, and array-like objects. These methods are convenient to use and are entirely compatible with any browser.
If you work with jQuery, you may use
jQuery.each()
method. It can be used to seamlessly iterate over both objects and arrays:
$.each(obj, function(key, value) {
console.log(key, value);
});
In Underscore.js you can find method
_.each()
, which iterates over a list of elements, yielding each in turn to a supplied function (pay attention to the order of arguments in iteratee function!):
_.each(obj, function(value, key) {
console.log(key, value);
});
Lo-Dash provides several methods for iterating over object properties. Basic
_.forEach()
(or it's alias_.each()
) is useful for looping through both objects and arrays, however (!) objects withlength
property are treated like arrays, and to avoid this behavior it is suggested to use_.forIn()
and_.forOwn()
methods (these also havevalue
argument coming first):
_.forIn(obj, function(value, key) {
console.log(key, value);
});
_.forIn()
iterates over own and inherited enumerable properties of an object, while_.forOwn()
iterates only over own properties of an object (basically checking againsthasOwnProperty
function). For simple objects and object literals any of these methods will work fine.
Generally all described methods have the same behaviour with any supplied objects. Besides using native for..in
loop will usually be faster than any abstraction, such as jQuery.each()
, these methods are considerably easier to use, require less coding and provide better error handling.
edited Jun 8 '16 at 19:43


meagar♦
180k29273293
180k29273293
answered Jan 20 '13 at 17:58


VisioNVisioN
112k24217231
112k24217231
4
To get to the value: $.each(obj, function (key, value) { console.log(value.title); });
– Ravi Ram
Jun 8 '13 at 14:41
2
Just funny how underscore and jquery changed parameters :)
– ppasler
Sep 8 '17 at 7:24
add a comment |
4
To get to the value: $.each(obj, function (key, value) { console.log(value.title); });
– Ravi Ram
Jun 8 '13 at 14:41
2
Just funny how underscore and jquery changed parameters :)
– ppasler
Sep 8 '17 at 7:24
4
4
To get to the value: $.each(obj, function (key, value) { console.log(value.title); });
– Ravi Ram
Jun 8 '13 at 14:41
To get to the value: $.each(obj, function (key, value) { console.log(value.title); });
– Ravi Ram
Jun 8 '13 at 14:41
2
2
Just funny how underscore and jquery changed parameters :)
– ppasler
Sep 8 '17 at 7:24
Just funny how underscore and jquery changed parameters :)
– ppasler
Sep 8 '17 at 7:24
add a comment |
In ECMAScript 5 you have new approach in iteration fields of literal - Object.keys
More information you can see on MDN
My choice is below as a faster solution in current versions of browsers (Chrome30, IE10, FF25)
var keys = Object.keys(p),
len = keys.length,
i = 0,
prop,
value;
while (i < len) {
prop = keys[i];
value = p[prop];
i += 1;
}
You can compare performance of this approach with different implementations on jsperf.com:
- Extend Implementations
- Object keys iteration
- object literal iteration
Browser support you can see on Kangax's compat table
For old browser you have simple and full polyfill
UPD:
performance comparison for all most popular cases in this question on perfjs.info
:
object literal iteration
Indeed, I just wanted to post this method. But you beat me to it :(
– Jamie Hutber
Mar 20 '14 at 23:05
jsperf.com/object-iteration-comparison
– Jason
Oct 26 '16 at 15:02
add a comment |
In ECMAScript 5 you have new approach in iteration fields of literal - Object.keys
More information you can see on MDN
My choice is below as a faster solution in current versions of browsers (Chrome30, IE10, FF25)
var keys = Object.keys(p),
len = keys.length,
i = 0,
prop,
value;
while (i < len) {
prop = keys[i];
value = p[prop];
i += 1;
}
You can compare performance of this approach with different implementations on jsperf.com:
- Extend Implementations
- Object keys iteration
- object literal iteration
Browser support you can see on Kangax's compat table
For old browser you have simple and full polyfill
UPD:
performance comparison for all most popular cases in this question on perfjs.info
:
object literal iteration
Indeed, I just wanted to post this method. But you beat me to it :(
– Jamie Hutber
Mar 20 '14 at 23:05
jsperf.com/object-iteration-comparison
– Jason
Oct 26 '16 at 15:02
add a comment |
In ECMAScript 5 you have new approach in iteration fields of literal - Object.keys
More information you can see on MDN
My choice is below as a faster solution in current versions of browsers (Chrome30, IE10, FF25)
var keys = Object.keys(p),
len = keys.length,
i = 0,
prop,
value;
while (i < len) {
prop = keys[i];
value = p[prop];
i += 1;
}
You can compare performance of this approach with different implementations on jsperf.com:
- Extend Implementations
- Object keys iteration
- object literal iteration
Browser support you can see on Kangax's compat table
For old browser you have simple and full polyfill
UPD:
performance comparison for all most popular cases in this question on perfjs.info
:
object literal iteration
In ECMAScript 5 you have new approach in iteration fields of literal - Object.keys
More information you can see on MDN
My choice is below as a faster solution in current versions of browsers (Chrome30, IE10, FF25)
var keys = Object.keys(p),
len = keys.length,
i = 0,
prop,
value;
while (i < len) {
prop = keys[i];
value = p[prop];
i += 1;
}
You can compare performance of this approach with different implementations on jsperf.com:
- Extend Implementations
- Object keys iteration
- object literal iteration
Browser support you can see on Kangax's compat table
For old browser you have simple and full polyfill
UPD:
performance comparison for all most popular cases in this question on perfjs.info
:
object literal iteration
edited Sep 12 '16 at 22:11
answered Nov 16 '13 at 19:59
PencroffPencroff
894813
894813
Indeed, I just wanted to post this method. But you beat me to it :(
– Jamie Hutber
Mar 20 '14 at 23:05
jsperf.com/object-iteration-comparison
– Jason
Oct 26 '16 at 15:02
add a comment |
Indeed, I just wanted to post this method. But you beat me to it :(
– Jamie Hutber
Mar 20 '14 at 23:05
jsperf.com/object-iteration-comparison
– Jason
Oct 26 '16 at 15:02
Indeed, I just wanted to post this method. But you beat me to it :(
– Jamie Hutber
Mar 20 '14 at 23:05
Indeed, I just wanted to post this method. But you beat me to it :(
– Jamie Hutber
Mar 20 '14 at 23:05
jsperf.com/object-iteration-comparison
– Jason
Oct 26 '16 at 15:02
jsperf.com/object-iteration-comparison
– Jason
Oct 26 '16 at 15:02
add a comment |
You can just iterate over it like:
for (var key in p) {
alert(p[key]);
}
Note that key
will not take on the value of the property, it's just an index value.
12
This is repeated and not even entirely correct. You need to have a check of hasOwnProperty to make this work properly
– Vatsal
Jun 2 '16 at 20:18
3
I initially downvoted this based on the above comment until i realized that this answer came first, therefore is not "repeated". It is possibly incomplete but works just fine for many cases.
– billynoah
Oct 9 '18 at 15:16
add a comment |
You can just iterate over it like:
for (var key in p) {
alert(p[key]);
}
Note that key
will not take on the value of the property, it's just an index value.
12
This is repeated and not even entirely correct. You need to have a check of hasOwnProperty to make this work properly
– Vatsal
Jun 2 '16 at 20:18
3
I initially downvoted this based on the above comment until i realized that this answer came first, therefore is not "repeated". It is possibly incomplete but works just fine for many cases.
– billynoah
Oct 9 '18 at 15:16
add a comment |
You can just iterate over it like:
for (var key in p) {
alert(p[key]);
}
Note that key
will not take on the value of the property, it's just an index value.
You can just iterate over it like:
for (var key in p) {
alert(p[key]);
}
Note that key
will not take on the value of the property, it's just an index value.
edited Oct 9 '18 at 15:11


billynoah
10.9k64367
10.9k64367
answered Mar 26 '09 at 6:05
BryanBryan
2,13962220
2,13962220
12
This is repeated and not even entirely correct. You need to have a check of hasOwnProperty to make this work properly
– Vatsal
Jun 2 '16 at 20:18
3
I initially downvoted this based on the above comment until i realized that this answer came first, therefore is not "repeated". It is possibly incomplete but works just fine for many cases.
– billynoah
Oct 9 '18 at 15:16
add a comment |
12
This is repeated and not even entirely correct. You need to have a check of hasOwnProperty to make this work properly
– Vatsal
Jun 2 '16 at 20:18
3
I initially downvoted this based on the above comment until i realized that this answer came first, therefore is not "repeated". It is possibly incomplete but works just fine for many cases.
– billynoah
Oct 9 '18 at 15:16
12
12
This is repeated and not even entirely correct. You need to have a check of hasOwnProperty to make this work properly
– Vatsal
Jun 2 '16 at 20:18
This is repeated and not even entirely correct. You need to have a check of hasOwnProperty to make this work properly
– Vatsal
Jun 2 '16 at 20:18
3
3
I initially downvoted this based on the above comment until i realized that this answer came first, therefore is not "repeated". It is possibly incomplete but works just fine for many cases.
– billynoah
Oct 9 '18 at 15:16
I initially downvoted this based on the above comment until i realized that this answer came first, therefore is not "repeated". It is possibly incomplete but works just fine for many cases.
– billynoah
Oct 9 '18 at 15:16
add a comment |
Preface:
- Object properties can be own (the property is on the object itself) or inherited (not on the object itself, on one of its prototypes).
- Object properties can be enumerable or non-enumerable. Non-enumerable properties are left out of lots of property enumerations/arrays.
- Property names can be strings or Symbols. Properties whose names are Symbols are left out of lots of property enumerations/arrays.
Here in 2018, your options for looping through an object's properties are:
for-in
[MDN, spec] — A loop structure that loops through the names of an object's enumerable properties, including inherited ones, whose names are strings
Object.keys
[MDN, spec] — A function providing an array of the names of an object's own, enumerable properties whose names are strings.
Object.values
[MDN, spec] — A function providing an array of the values of an object's own, enumerable properties.
Object.entries
[MDN, spec] — A function providing an array of the names and values of an object's own, enumerable properties.
Object.getOwnPropertyNames
[MDN, spec] — A function providing an array of the names of an object's own properties (even non-enumerable ones) whose names are strings.
Object.getOwnPropertySymbols
[MDN, spec] — A function providing an array of the names of an object's own properties (even non-enumerable ones) whose names are Symbols.
Reflect.ownKeys
[MDN, spec] — A function providing an array of the names of an object's own properties (even non-enumerable ones), whether those names are strings or Symbols.- If you want all of an object's properties, including non-enumerable inherited ones, you need to use a loop and
Object.getPrototypeOf
[MDN, spec] and useObject.getOwnPropertyNames
,Object.getOwnPropertySymbols
, orReflect.ownKeys
on each object in the prototype chain (example at the bottom of this answer).
With all of them except for-in
, you'd use some kind of looping construct on the array (for
, for-of
, forEach
, etc.).
Examples:
for-in
:
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name in o) {
const value = o[name];
console.log(`${name} = ${value}`);
}
Object.keys
(with a for-of
loop, but you can use any looping construct):
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name of Object.keys(o)) {
const value = o[name];
console.log(`${name} = ${value}`);
}
Object.values
:
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const value of Object.values(o)) {
console.log(`${value}`);
}
Object.entries
:
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const [name, value] of Object.entries(o)) {
console.log(`${name} = ${value}`);
}
Object.getOwnPropertyNames
:
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name of Object.getOwnPropertyNames(o)) {
const value = o[name];
console.log(`${name} = ${value}`);
}
Object.getOwnPropertySymbols
:
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name of Object.getOwnPropertySymbols(o)) {
const value = o[name];
console.log(`${String(name)} = ${value}`);
}
Reflect.ownKeys
:
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name of Reflect.ownKeys(o)) {
const value = o[name];
console.log(`${String(name)} = ${value}`);
}
All properties, including inherited non-enumerable ones:
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (let depth = 0, current = o; current; ++depth, current = Object.getPrototypeOf(current)) {
for (const name of Reflect.ownKeys(current)) {
const value = o[name];
console.log(`[${depth}] ${String(name)} = ${String(value)}`);
}
}
.as-console-wrapper {
max-height: 100% !important;
}
add a comment |
Preface:
- Object properties can be own (the property is on the object itself) or inherited (not on the object itself, on one of its prototypes).
- Object properties can be enumerable or non-enumerable. Non-enumerable properties are left out of lots of property enumerations/arrays.
- Property names can be strings or Symbols. Properties whose names are Symbols are left out of lots of property enumerations/arrays.
Here in 2018, your options for looping through an object's properties are:
for-in
[MDN, spec] — A loop structure that loops through the names of an object's enumerable properties, including inherited ones, whose names are strings
Object.keys
[MDN, spec] — A function providing an array of the names of an object's own, enumerable properties whose names are strings.
Object.values
[MDN, spec] — A function providing an array of the values of an object's own, enumerable properties.
Object.entries
[MDN, spec] — A function providing an array of the names and values of an object's own, enumerable properties.
Object.getOwnPropertyNames
[MDN, spec] — A function providing an array of the names of an object's own properties (even non-enumerable ones) whose names are strings.
Object.getOwnPropertySymbols
[MDN, spec] — A function providing an array of the names of an object's own properties (even non-enumerable ones) whose names are Symbols.
Reflect.ownKeys
[MDN, spec] — A function providing an array of the names of an object's own properties (even non-enumerable ones), whether those names are strings or Symbols.- If you want all of an object's properties, including non-enumerable inherited ones, you need to use a loop and
Object.getPrototypeOf
[MDN, spec] and useObject.getOwnPropertyNames
,Object.getOwnPropertySymbols
, orReflect.ownKeys
on each object in the prototype chain (example at the bottom of this answer).
With all of them except for-in
, you'd use some kind of looping construct on the array (for
, for-of
, forEach
, etc.).
Examples:
for-in
:
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name in o) {
const value = o[name];
console.log(`${name} = ${value}`);
}
Object.keys
(with a for-of
loop, but you can use any looping construct):
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name of Object.keys(o)) {
const value = o[name];
console.log(`${name} = ${value}`);
}
Object.values
:
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const value of Object.values(o)) {
console.log(`${value}`);
}
Object.entries
:
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const [name, value] of Object.entries(o)) {
console.log(`${name} = ${value}`);
}
Object.getOwnPropertyNames
:
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name of Object.getOwnPropertyNames(o)) {
const value = o[name];
console.log(`${name} = ${value}`);
}
Object.getOwnPropertySymbols
:
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name of Object.getOwnPropertySymbols(o)) {
const value = o[name];
console.log(`${String(name)} = ${value}`);
}
Reflect.ownKeys
:
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name of Reflect.ownKeys(o)) {
const value = o[name];
console.log(`${String(name)} = ${value}`);
}
All properties, including inherited non-enumerable ones:
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (let depth = 0, current = o; current; ++depth, current = Object.getPrototypeOf(current)) {
for (const name of Reflect.ownKeys(current)) {
const value = o[name];
console.log(`[${depth}] ${String(name)} = ${String(value)}`);
}
}
.as-console-wrapper {
max-height: 100% !important;
}
add a comment |
Preface:
- Object properties can be own (the property is on the object itself) or inherited (not on the object itself, on one of its prototypes).
- Object properties can be enumerable or non-enumerable. Non-enumerable properties are left out of lots of property enumerations/arrays.
- Property names can be strings or Symbols. Properties whose names are Symbols are left out of lots of property enumerations/arrays.
Here in 2018, your options for looping through an object's properties are:
for-in
[MDN, spec] — A loop structure that loops through the names of an object's enumerable properties, including inherited ones, whose names are strings
Object.keys
[MDN, spec] — A function providing an array of the names of an object's own, enumerable properties whose names are strings.
Object.values
[MDN, spec] — A function providing an array of the values of an object's own, enumerable properties.
Object.entries
[MDN, spec] — A function providing an array of the names and values of an object's own, enumerable properties.
Object.getOwnPropertyNames
[MDN, spec] — A function providing an array of the names of an object's own properties (even non-enumerable ones) whose names are strings.
Object.getOwnPropertySymbols
[MDN, spec] — A function providing an array of the names of an object's own properties (even non-enumerable ones) whose names are Symbols.
Reflect.ownKeys
[MDN, spec] — A function providing an array of the names of an object's own properties (even non-enumerable ones), whether those names are strings or Symbols.- If you want all of an object's properties, including non-enumerable inherited ones, you need to use a loop and
Object.getPrototypeOf
[MDN, spec] and useObject.getOwnPropertyNames
,Object.getOwnPropertySymbols
, orReflect.ownKeys
on each object in the prototype chain (example at the bottom of this answer).
With all of them except for-in
, you'd use some kind of looping construct on the array (for
, for-of
, forEach
, etc.).
Examples:
for-in
:
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name in o) {
const value = o[name];
console.log(`${name} = ${value}`);
}
Object.keys
(with a for-of
loop, but you can use any looping construct):
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name of Object.keys(o)) {
const value = o[name];
console.log(`${name} = ${value}`);
}
Object.values
:
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const value of Object.values(o)) {
console.log(`${value}`);
}
Object.entries
:
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const [name, value] of Object.entries(o)) {
console.log(`${name} = ${value}`);
}
Object.getOwnPropertyNames
:
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name of Object.getOwnPropertyNames(o)) {
const value = o[name];
console.log(`${name} = ${value}`);
}
Object.getOwnPropertySymbols
:
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name of Object.getOwnPropertySymbols(o)) {
const value = o[name];
console.log(`${String(name)} = ${value}`);
}
Reflect.ownKeys
:
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name of Reflect.ownKeys(o)) {
const value = o[name];
console.log(`${String(name)} = ${value}`);
}
All properties, including inherited non-enumerable ones:
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (let depth = 0, current = o; current; ++depth, current = Object.getPrototypeOf(current)) {
for (const name of Reflect.ownKeys(current)) {
const value = o[name];
console.log(`[${depth}] ${String(name)} = ${String(value)}`);
}
}
.as-console-wrapper {
max-height: 100% !important;
}
Preface:
- Object properties can be own (the property is on the object itself) or inherited (not on the object itself, on one of its prototypes).
- Object properties can be enumerable or non-enumerable. Non-enumerable properties are left out of lots of property enumerations/arrays.
- Property names can be strings or Symbols. Properties whose names are Symbols are left out of lots of property enumerations/arrays.
Here in 2018, your options for looping through an object's properties are:
for-in
[MDN, spec] — A loop structure that loops through the names of an object's enumerable properties, including inherited ones, whose names are strings
Object.keys
[MDN, spec] — A function providing an array of the names of an object's own, enumerable properties whose names are strings.
Object.values
[MDN, spec] — A function providing an array of the values of an object's own, enumerable properties.
Object.entries
[MDN, spec] — A function providing an array of the names and values of an object's own, enumerable properties.
Object.getOwnPropertyNames
[MDN, spec] — A function providing an array of the names of an object's own properties (even non-enumerable ones) whose names are strings.
Object.getOwnPropertySymbols
[MDN, spec] — A function providing an array of the names of an object's own properties (even non-enumerable ones) whose names are Symbols.
Reflect.ownKeys
[MDN, spec] — A function providing an array of the names of an object's own properties (even non-enumerable ones), whether those names are strings or Symbols.- If you want all of an object's properties, including non-enumerable inherited ones, you need to use a loop and
Object.getPrototypeOf
[MDN, spec] and useObject.getOwnPropertyNames
,Object.getOwnPropertySymbols
, orReflect.ownKeys
on each object in the prototype chain (example at the bottom of this answer).
With all of them except for-in
, you'd use some kind of looping construct on the array (for
, for-of
, forEach
, etc.).
Examples:
for-in
:
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name in o) {
const value = o[name];
console.log(`${name} = ${value}`);
}
Object.keys
(with a for-of
loop, but you can use any looping construct):
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name of Object.keys(o)) {
const value = o[name];
console.log(`${name} = ${value}`);
}
Object.values
:
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const value of Object.values(o)) {
console.log(`${value}`);
}
Object.entries
:
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const [name, value] of Object.entries(o)) {
console.log(`${name} = ${value}`);
}
Object.getOwnPropertyNames
:
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name of Object.getOwnPropertyNames(o)) {
const value = o[name];
console.log(`${name} = ${value}`);
}
Object.getOwnPropertySymbols
:
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name of Object.getOwnPropertySymbols(o)) {
const value = o[name];
console.log(`${String(name)} = ${value}`);
}
Reflect.ownKeys
:
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name of Reflect.ownKeys(o)) {
const value = o[name];
console.log(`${String(name)} = ${value}`);
}
All properties, including inherited non-enumerable ones:
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (let depth = 0, current = o; current; ++depth, current = Object.getPrototypeOf(current)) {
for (const name of Reflect.ownKeys(current)) {
const value = o[name];
console.log(`[${depth}] ${String(name)} = ${String(value)}`);
}
}
.as-console-wrapper {
max-height: 100% !important;
}
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name in o) {
const value = o[name];
console.log(`${name} = ${value}`);
}
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name in o) {
const value = o[name];
console.log(`${name} = ${value}`);
}
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name of Object.keys(o)) {
const value = o[name];
console.log(`${name} = ${value}`);
}
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name of Object.keys(o)) {
const value = o[name];
console.log(`${name} = ${value}`);
}
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const value of Object.values(o)) {
console.log(`${value}`);
}
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const value of Object.values(o)) {
console.log(`${value}`);
}
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const [name, value] of Object.entries(o)) {
console.log(`${name} = ${value}`);
}
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const [name, value] of Object.entries(o)) {
console.log(`${name} = ${value}`);
}
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name of Object.getOwnPropertyNames(o)) {
const value = o[name];
console.log(`${name} = ${value}`);
}
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name of Object.getOwnPropertyNames(o)) {
const value = o[name];
console.log(`${name} = ${value}`);
}
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name of Object.getOwnPropertySymbols(o)) {
const value = o[name];
console.log(`${String(name)} = ${value}`);
}
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name of Object.getOwnPropertySymbols(o)) {
const value = o[name];
console.log(`${String(name)} = ${value}`);
}
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name of Reflect.ownKeys(o)) {
const value = o[name];
console.log(`${String(name)} = ${value}`);
}
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name of Reflect.ownKeys(o)) {
const value = o[name];
console.log(`${String(name)} = ${value}`);
}
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (let depth = 0, current = o; current; ++depth, current = Object.getPrototypeOf(current)) {
for (const name of Reflect.ownKeys(current)) {
const value = o[name];
console.log(`[${depth}] ${String(name)} = ${String(value)}`);
}
}
.as-console-wrapper {
max-height: 100% !important;
}
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (let depth = 0, current = o; current; ++depth, current = Object.getPrototypeOf(current)) {
for (const name of Reflect.ownKeys(current)) {
const value = o[name];
console.log(`[${depth}] ${String(name)} = ${String(value)}`);
}
}
.as-console-wrapper {
max-height: 100% !important;
}
answered Jul 10 '18 at 10:39
T.J. CrowderT.J. Crowder
692k12212311326
692k12212311326
add a comment |
add a comment |
Since es2015 is getting more and more popular I am posting this answer which include usage of generator and iterator to smoothly iterate through [key, value]
pairs. As it is possible in other languages for instance Ruby.
Ok here is a code:
const MyObject = {
'a': 'Hello',
'b': 'it's',
'c': 'me',
'd': 'you',
'e': 'looking',
'f': 'for',
[Symbol.iterator]: function* () {
for (const i of Object.keys(this)) {
yield [i, this[i]];
}
}
};
for (const [k, v] of MyObject) {
console.log(`Here is key ${k} and here is value ${v}`);
}
All information about how can you do an iterator and generator you can find at developer Mozilla page.
Hope It helped someone.
EDIT:
ES2017 will include Object.entries
which will make iterating over [key, value]
pairs in objects even more easier. It is now known that it will be a part of a standard according to the ts39 stage information.
I think it is time to update my answer to let it became even more fresher than it's now.
const MyObject = {
'a': 'Hello',
'b': 'it's',
'c': 'me',
'd': 'you',
'e': 'looking',
'f': 'for',
};
for (const [k, v] of Object.entries(MyObject)) {
console.log(`Here is key ${k} and here is value ${v}`);
}
You can find more about usage on
MDN page
This looks totally superfluous/unneeded to me. Would you add it to every object in your system? I thought the point of providing an iterator was so that you could do `for( const [k, v] of myObject )'. It just looks like extra code providing little additional value.
– Dean Radcliffe
Sep 28 '17 at 16:36
add a comment |
Since es2015 is getting more and more popular I am posting this answer which include usage of generator and iterator to smoothly iterate through [key, value]
pairs. As it is possible in other languages for instance Ruby.
Ok here is a code:
const MyObject = {
'a': 'Hello',
'b': 'it's',
'c': 'me',
'd': 'you',
'e': 'looking',
'f': 'for',
[Symbol.iterator]: function* () {
for (const i of Object.keys(this)) {
yield [i, this[i]];
}
}
};
for (const [k, v] of MyObject) {
console.log(`Here is key ${k} and here is value ${v}`);
}
All information about how can you do an iterator and generator you can find at developer Mozilla page.
Hope It helped someone.
EDIT:
ES2017 will include Object.entries
which will make iterating over [key, value]
pairs in objects even more easier. It is now known that it will be a part of a standard according to the ts39 stage information.
I think it is time to update my answer to let it became even more fresher than it's now.
const MyObject = {
'a': 'Hello',
'b': 'it's',
'c': 'me',
'd': 'you',
'e': 'looking',
'f': 'for',
};
for (const [k, v] of Object.entries(MyObject)) {
console.log(`Here is key ${k} and here is value ${v}`);
}
You can find more about usage on
MDN page
This looks totally superfluous/unneeded to me. Would you add it to every object in your system? I thought the point of providing an iterator was so that you could do `for( const [k, v] of myObject )'. It just looks like extra code providing little additional value.
– Dean Radcliffe
Sep 28 '17 at 16:36
add a comment |
Since es2015 is getting more and more popular I am posting this answer which include usage of generator and iterator to smoothly iterate through [key, value]
pairs. As it is possible in other languages for instance Ruby.
Ok here is a code:
const MyObject = {
'a': 'Hello',
'b': 'it's',
'c': 'me',
'd': 'you',
'e': 'looking',
'f': 'for',
[Symbol.iterator]: function* () {
for (const i of Object.keys(this)) {
yield [i, this[i]];
}
}
};
for (const [k, v] of MyObject) {
console.log(`Here is key ${k} and here is value ${v}`);
}
All information about how can you do an iterator and generator you can find at developer Mozilla page.
Hope It helped someone.
EDIT:
ES2017 will include Object.entries
which will make iterating over [key, value]
pairs in objects even more easier. It is now known that it will be a part of a standard according to the ts39 stage information.
I think it is time to update my answer to let it became even more fresher than it's now.
const MyObject = {
'a': 'Hello',
'b': 'it's',
'c': 'me',
'd': 'you',
'e': 'looking',
'f': 'for',
};
for (const [k, v] of Object.entries(MyObject)) {
console.log(`Here is key ${k} and here is value ${v}`);
}
You can find more about usage on
MDN page
Since es2015 is getting more and more popular I am posting this answer which include usage of generator and iterator to smoothly iterate through [key, value]
pairs. As it is possible in other languages for instance Ruby.
Ok here is a code:
const MyObject = {
'a': 'Hello',
'b': 'it's',
'c': 'me',
'd': 'you',
'e': 'looking',
'f': 'for',
[Symbol.iterator]: function* () {
for (const i of Object.keys(this)) {
yield [i, this[i]];
}
}
};
for (const [k, v] of MyObject) {
console.log(`Here is key ${k} and here is value ${v}`);
}
All information about how can you do an iterator and generator you can find at developer Mozilla page.
Hope It helped someone.
EDIT:
ES2017 will include Object.entries
which will make iterating over [key, value]
pairs in objects even more easier. It is now known that it will be a part of a standard according to the ts39 stage information.
I think it is time to update my answer to let it became even more fresher than it's now.
const MyObject = {
'a': 'Hello',
'b': 'it's',
'c': 'me',
'd': 'you',
'e': 'looking',
'f': 'for',
};
for (const [k, v] of Object.entries(MyObject)) {
console.log(`Here is key ${k} and here is value ${v}`);
}
You can find more about usage on
MDN page
edited Jul 30 '17 at 14:34
answered Aug 27 '16 at 9:06
FieryCodFieryCod
793821
793821
This looks totally superfluous/unneeded to me. Would you add it to every object in your system? I thought the point of providing an iterator was so that you could do `for( const [k, v] of myObject )'. It just looks like extra code providing little additional value.
– Dean Radcliffe
Sep 28 '17 at 16:36
add a comment |
This looks totally superfluous/unneeded to me. Would you add it to every object in your system? I thought the point of providing an iterator was so that you could do `for( const [k, v] of myObject )'. It just looks like extra code providing little additional value.
– Dean Radcliffe
Sep 28 '17 at 16:36
This looks totally superfluous/unneeded to me. Would you add it to every object in your system? I thought the point of providing an iterator was so that you could do `for( const [k, v] of myObject )'. It just looks like extra code providing little additional value.
– Dean Radcliffe
Sep 28 '17 at 16:36
This looks totally superfluous/unneeded to me. Would you add it to every object in your system? I thought the point of providing an iterator was so that you could do `for( const [k, v] of myObject )'. It just looks like extra code providing little additional value.
– Dean Radcliffe
Sep 28 '17 at 16:36
add a comment |
via prototype with forEach() which should skip the prototype chain properties:
Object.prototype.each = function(f) {
var obj = this
Object.keys(obj).forEach( function(key) {
f( key , obj[key] )
});
}
//print all keys and values
var obj = {a:1,b:2,c:3}
obj.each(function(key,value) { console.log(key + " " + value) });
// a 1
// b 2
// c 3
2
Be careful with the prototype:obj = { print: 1, each: 2, word: 3 }
producesTypeError: number is not a function
. UsingforEach
to match the similarArray
function may reduce the risk somewhat.
– David Harkness
Jun 23 '14 at 21:40
add a comment |
via prototype with forEach() which should skip the prototype chain properties:
Object.prototype.each = function(f) {
var obj = this
Object.keys(obj).forEach( function(key) {
f( key , obj[key] )
});
}
//print all keys and values
var obj = {a:1,b:2,c:3}
obj.each(function(key,value) { console.log(key + " " + value) });
// a 1
// b 2
// c 3
2
Be careful with the prototype:obj = { print: 1, each: 2, word: 3 }
producesTypeError: number is not a function
. UsingforEach
to match the similarArray
function may reduce the risk somewhat.
– David Harkness
Jun 23 '14 at 21:40
add a comment |
via prototype with forEach() which should skip the prototype chain properties:
Object.prototype.each = function(f) {
var obj = this
Object.keys(obj).forEach( function(key) {
f( key , obj[key] )
});
}
//print all keys and values
var obj = {a:1,b:2,c:3}
obj.each(function(key,value) { console.log(key + " " + value) });
// a 1
// b 2
// c 3
via prototype with forEach() which should skip the prototype chain properties:
Object.prototype.each = function(f) {
var obj = this
Object.keys(obj).forEach( function(key) {
f( key , obj[key] )
});
}
//print all keys and values
var obj = {a:1,b:2,c:3}
obj.each(function(key,value) { console.log(key + " " + value) });
// a 1
// b 2
// c 3
answered Dec 9 '12 at 5:05


bitstriderbitstrider
2,9481527
2,9481527
2
Be careful with the prototype:obj = { print: 1, each: 2, word: 3 }
producesTypeError: number is not a function
. UsingforEach
to match the similarArray
function may reduce the risk somewhat.
– David Harkness
Jun 23 '14 at 21:40
add a comment |
2
Be careful with the prototype:obj = { print: 1, each: 2, word: 3 }
producesTypeError: number is not a function
. UsingforEach
to match the similarArray
function may reduce the risk somewhat.
– David Harkness
Jun 23 '14 at 21:40
2
2
Be careful with the prototype:
obj = { print: 1, each: 2, word: 3 }
produces TypeError: number is not a function
. Using forEach
to match the similar Array
function may reduce the risk somewhat.– David Harkness
Jun 23 '14 at 21:40
Be careful with the prototype:
obj = { print: 1, each: 2, word: 3 }
produces TypeError: number is not a function
. Using forEach
to match the similar Array
function may reduce the risk somewhat.– David Harkness
Jun 23 '14 at 21:40
add a comment |
After looking through all the answers in here, hasOwnProperty isn't required for my own usage because my json object is clean; there's really no sense in adding any additional javascript processing. This is all I'm using:
for (var key in p) {
console.log(key + ' => ' + p[key]);
// key is key
// value is p[key]
}
18
Whether the JSON object is clean or not is irrelevant. If at any other time some code sets a property onObject.prototype
, then it will be enumerated byfor..in
. If you are sure you are not using any libraries that do that, then you don't need to callhasOwnProperty
.
– G-Wiz
Jan 13 '12 at 20:15
3
It can be completely clean if created withObject.create(null)
– Juan Mendes
Apr 14 '16 at 11:37
add a comment |
After looking through all the answers in here, hasOwnProperty isn't required for my own usage because my json object is clean; there's really no sense in adding any additional javascript processing. This is all I'm using:
for (var key in p) {
console.log(key + ' => ' + p[key]);
// key is key
// value is p[key]
}
18
Whether the JSON object is clean or not is irrelevant. If at any other time some code sets a property onObject.prototype
, then it will be enumerated byfor..in
. If you are sure you are not using any libraries that do that, then you don't need to callhasOwnProperty
.
– G-Wiz
Jan 13 '12 at 20:15
3
It can be completely clean if created withObject.create(null)
– Juan Mendes
Apr 14 '16 at 11:37
add a comment |
After looking through all the answers in here, hasOwnProperty isn't required for my own usage because my json object is clean; there's really no sense in adding any additional javascript processing. This is all I'm using:
for (var key in p) {
console.log(key + ' => ' + p[key]);
// key is key
// value is p[key]
}
After looking through all the answers in here, hasOwnProperty isn't required for my own usage because my json object is clean; there's really no sense in adding any additional javascript processing. This is all I'm using:
for (var key in p) {
console.log(key + ' => ' + p[key]);
// key is key
// value is p[key]
}
answered Aug 18 '11 at 20:50
Francis LewisFrancis Lewis
6,05974557
6,05974557
18
Whether the JSON object is clean or not is irrelevant. If at any other time some code sets a property onObject.prototype
, then it will be enumerated byfor..in
. If you are sure you are not using any libraries that do that, then you don't need to callhasOwnProperty
.
– G-Wiz
Jan 13 '12 at 20:15
3
It can be completely clean if created withObject.create(null)
– Juan Mendes
Apr 14 '16 at 11:37
add a comment |
18
Whether the JSON object is clean or not is irrelevant. If at any other time some code sets a property onObject.prototype
, then it will be enumerated byfor..in
. If you are sure you are not using any libraries that do that, then you don't need to callhasOwnProperty
.
– G-Wiz
Jan 13 '12 at 20:15
3
It can be completely clean if created withObject.create(null)
– Juan Mendes
Apr 14 '16 at 11:37
18
18
Whether the JSON object is clean or not is irrelevant. If at any other time some code sets a property on
Object.prototype
, then it will be enumerated by for..in
. If you are sure you are not using any libraries that do that, then you don't need to call hasOwnProperty
.– G-Wiz
Jan 13 '12 at 20:15
Whether the JSON object is clean or not is irrelevant. If at any other time some code sets a property on
Object.prototype
, then it will be enumerated by for..in
. If you are sure you are not using any libraries that do that, then you don't need to call hasOwnProperty
.– G-Wiz
Jan 13 '12 at 20:15
3
3
It can be completely clean if created with
Object.create(null)
– Juan Mendes
Apr 14 '16 at 11:37
It can be completely clean if created with
Object.create(null)
– Juan Mendes
Apr 14 '16 at 11:37
add a comment |
for(key in p) {
alert( p[key] );
}
Note: you can do this over arrays, but you'll iterate over the length
and other properties, too.
4
When using a for loop like that,key
will just take on an index value, so that will just alert 0, 1, 2, etc... You need to access p[key].
– Bryan
Mar 26 '09 at 6:07
1
It is the slowest method of array iteration in JavaScript. You can check this on your computer - Best way to iterate over Arrays in JavaScript
– Pencroff
Dec 5 '13 at 12:15
5
@Pencroff: the problem is that the question is not about looping through arrays... ;)
– Sk8erPeter
Jan 1 '14 at 0:55
This is something I don't understand on stackoverflow. Richard gave the correct answer, and he was the first one giving that answer, but he did not get any +1? @Bryanvar p = {"p1":"q","p2":"w"}; for(key in p) { alert( key ); }
is popping "p1" and "p2" in alerts, so whats wrong about that???
– Sebastian
Aug 5 '14 at 6:43
5
I think the main difference is the quality: the other answers not only tell how, but also tell the caveats (e.g., the prototype) and how to deal with those caveats. IMHO, those other answers are better than mine :).
– Richard Levasseur
Aug 6 '14 at 16:41
add a comment |
for(key in p) {
alert( p[key] );
}
Note: you can do this over arrays, but you'll iterate over the length
and other properties, too.
4
When using a for loop like that,key
will just take on an index value, so that will just alert 0, 1, 2, etc... You need to access p[key].
– Bryan
Mar 26 '09 at 6:07
1
It is the slowest method of array iteration in JavaScript. You can check this on your computer - Best way to iterate over Arrays in JavaScript
– Pencroff
Dec 5 '13 at 12:15
5
@Pencroff: the problem is that the question is not about looping through arrays... ;)
– Sk8erPeter
Jan 1 '14 at 0:55
This is something I don't understand on stackoverflow. Richard gave the correct answer, and he was the first one giving that answer, but he did not get any +1? @Bryanvar p = {"p1":"q","p2":"w"}; for(key in p) { alert( key ); }
is popping "p1" and "p2" in alerts, so whats wrong about that???
– Sebastian
Aug 5 '14 at 6:43
5
I think the main difference is the quality: the other answers not only tell how, but also tell the caveats (e.g., the prototype) and how to deal with those caveats. IMHO, those other answers are better than mine :).
– Richard Levasseur
Aug 6 '14 at 16:41
add a comment |
for(key in p) {
alert( p[key] );
}
Note: you can do this over arrays, but you'll iterate over the length
and other properties, too.
for(key in p) {
alert( p[key] );
}
Note: you can do this over arrays, but you'll iterate over the length
and other properties, too.
edited Nov 3 '12 at 21:46


Kristian
13.8k872128
13.8k872128
answered Mar 26 '09 at 6:04
Richard LevasseurRichard Levasseur
9,87854155
9,87854155
4
When using a for loop like that,key
will just take on an index value, so that will just alert 0, 1, 2, etc... You need to access p[key].
– Bryan
Mar 26 '09 at 6:07
1
It is the slowest method of array iteration in JavaScript. You can check this on your computer - Best way to iterate over Arrays in JavaScript
– Pencroff
Dec 5 '13 at 12:15
5
@Pencroff: the problem is that the question is not about looping through arrays... ;)
– Sk8erPeter
Jan 1 '14 at 0:55
This is something I don't understand on stackoverflow. Richard gave the correct answer, and he was the first one giving that answer, but he did not get any +1? @Bryanvar p = {"p1":"q","p2":"w"}; for(key in p) { alert( key ); }
is popping "p1" and "p2" in alerts, so whats wrong about that???
– Sebastian
Aug 5 '14 at 6:43
5
I think the main difference is the quality: the other answers not only tell how, but also tell the caveats (e.g., the prototype) and how to deal with those caveats. IMHO, those other answers are better than mine :).
– Richard Levasseur
Aug 6 '14 at 16:41
add a comment |
4
When using a for loop like that,key
will just take on an index value, so that will just alert 0, 1, 2, etc... You need to access p[key].
– Bryan
Mar 26 '09 at 6:07
1
It is the slowest method of array iteration in JavaScript. You can check this on your computer - Best way to iterate over Arrays in JavaScript
– Pencroff
Dec 5 '13 at 12:15
5
@Pencroff: the problem is that the question is not about looping through arrays... ;)
– Sk8erPeter
Jan 1 '14 at 0:55
This is something I don't understand on stackoverflow. Richard gave the correct answer, and he was the first one giving that answer, but he did not get any +1? @Bryanvar p = {"p1":"q","p2":"w"}; for(key in p) { alert( key ); }
is popping "p1" and "p2" in alerts, so whats wrong about that???
– Sebastian
Aug 5 '14 at 6:43
5
I think the main difference is the quality: the other answers not only tell how, but also tell the caveats (e.g., the prototype) and how to deal with those caveats. IMHO, those other answers are better than mine :).
– Richard Levasseur
Aug 6 '14 at 16:41
4
4
When using a for loop like that,
key
will just take on an index value, so that will just alert 0, 1, 2, etc... You need to access p[key].– Bryan
Mar 26 '09 at 6:07
When using a for loop like that,
key
will just take on an index value, so that will just alert 0, 1, 2, etc... You need to access p[key].– Bryan
Mar 26 '09 at 6:07
1
1
It is the slowest method of array iteration in JavaScript. You can check this on your computer - Best way to iterate over Arrays in JavaScript
– Pencroff
Dec 5 '13 at 12:15
It is the slowest method of array iteration in JavaScript. You can check this on your computer - Best way to iterate over Arrays in JavaScript
– Pencroff
Dec 5 '13 at 12:15
5
5
@Pencroff: the problem is that the question is not about looping through arrays... ;)
– Sk8erPeter
Jan 1 '14 at 0:55
@Pencroff: the problem is that the question is not about looping through arrays... ;)
– Sk8erPeter
Jan 1 '14 at 0:55
This is something I don't understand on stackoverflow. Richard gave the correct answer, and he was the first one giving that answer, but he did not get any +1? @Bryan
var p = {"p1":"q","p2":"w"}; for(key in p) { alert( key ); }
is popping "p1" and "p2" in alerts, so whats wrong about that???– Sebastian
Aug 5 '14 at 6:43
This is something I don't understand on stackoverflow. Richard gave the correct answer, and he was the first one giving that answer, but he did not get any +1? @Bryan
var p = {"p1":"q","p2":"w"}; for(key in p) { alert( key ); }
is popping "p1" and "p2" in alerts, so whats wrong about that???– Sebastian
Aug 5 '14 at 6:43
5
5
I think the main difference is the quality: the other answers not only tell how, but also tell the caveats (e.g., the prototype) and how to deal with those caveats. IMHO, those other answers are better than mine :).
– Richard Levasseur
Aug 6 '14 at 16:41
I think the main difference is the quality: the other answers not only tell how, but also tell the caveats (e.g., the prototype) and how to deal with those caveats. IMHO, those other answers are better than mine :).
– Richard Levasseur
Aug 6 '14 at 16:41
add a comment |
It's interesting people in these answers have touched on both Object.keys()
and for...of
but never combined them:
var map = {well:'hello', there:'!'};
for (let key of Object.keys(map))
console.log(key + ':' + map[key]);
You can't just for...of
an Object
because it's not an iterator, and for...index
or .forEach()
ing the Object.keys()
is ugly/inefficient.
I'm glad most people are refraining from for...in
(with or without checking .hasOwnProperty()
) as that's also a bit messy, so other than my answer above, I'm here to say...
You can make ordinary object associations iterate! Behaving just like Map
s with direct use of the fancy for...of
DEMO working in Chrome and FF (I assume ES6 only)
var ordinaryObject = {well:'hello', there:'!'};
for (let pair of ordinaryObject)
//key:value
console.log(pair[0] + ':' + pair[1]);
//or
for (let [key, value] of ordinaryObject)
console.log(key + ':' + value);
So long as you include my shim below:
//makes all objects iterable just like Maps!!! YAY
//iterates over Object.keys() (which already ignores prototype chain for us)
Object.prototype[Symbol.iterator] = function() {
var keys = Object.keys(this)[Symbol.iterator]();
var obj = this;
var output;
return {next:function() {
if (!(output = keys.next()).done)
output.value = [output.value, obj[output.value]];
return output;
}};
};
Without having to create a real Map object that doesn't have the nice syntactic sugar.
var trueMap = new Map([['well', 'hello'], ['there', '!']]);
for (let pair of trueMap)
console.log(pair[0] + ':' + pair[1]);
In fact, with this shim, if you still wanted to take advantage of Map's other functionality (without shimming them all in) but still wanted to use the neat object notation, since objects are now iterable you can now just make a Map from it!
//shown in demo
var realMap = new Map({well:'hello', there:'!'});
For those who don't like to shim, or mess with prototype
in general, feel free to make the function on window instead, calling it something like getObjIterator()
then;
//no prototype manipulation
function getObjIterator(obj) {
//create a dummy object instead of adding functionality to all objects
var iterator = new Object();
//give it what the shim does but as its own local property
iterator[Symbol.iterator] = function() {
var keys = Object.keys(obj)[Symbol.iterator]();
var output;
return {next:function() {
if (!(output = keys.next()).done)
output.value = [output.value, obj[output.value]];
return output;
}};
};
return iterator;
}
Now you can just call it as an ordinary function, nothing else is affected
var realMap = new Map(getObjIterator({well:'hello', there:'!'}))
or
for (let pair of getObjIterator(ordinaryObject))
There's no reason why that wouldn't work.
Welcome to the future.
1
Case in point. So long as people scroll down and find it helpful, that's all that matters. Usually it's me trying to do something, not liking the stuff I see online, end up figuring it out, then I come back to share. It's good doco, I've actually come across my own answers before googling things I completely forgot about!
– Hashbrown
Jul 22 '16 at 6:57
@HelpMeStackOverflowMyOnlyHope Personally I do not like modifying the prototypes of objects I did not define myself.
– Janus Troelsen
Sep 30 '16 at 10:19
@JanusTroelsen did you even read the whole answer?For those who don't like to shim, or mess with prototype in general, feel free to make the function on window instead, calling it something like getObjIterator() then;
– Hashbrown
Sep 30 '16 at 12:58
Note that this technique doesn't work on plain objects, but useful nonetheless.
– noɥʇʎԀʎzɐɹƆ
Jun 14 '18 at 15:17
it does work for plain objects, that's literally the whole point (as well as the variable names likeordinaryObject
for emphasis that the magic still works for those types). Did you check the demos; what isn't working for you, @noɥʇʎԀʎzɐɹƆ? (P.S. your SE profile image is boss)
– Hashbrown
Jun 15 '18 at 6:47
|
show 2 more comments
It's interesting people in these answers have touched on both Object.keys()
and for...of
but never combined them:
var map = {well:'hello', there:'!'};
for (let key of Object.keys(map))
console.log(key + ':' + map[key]);
You can't just for...of
an Object
because it's not an iterator, and for...index
or .forEach()
ing the Object.keys()
is ugly/inefficient.
I'm glad most people are refraining from for...in
(with or without checking .hasOwnProperty()
) as that's also a bit messy, so other than my answer above, I'm here to say...
You can make ordinary object associations iterate! Behaving just like Map
s with direct use of the fancy for...of
DEMO working in Chrome and FF (I assume ES6 only)
var ordinaryObject = {well:'hello', there:'!'};
for (let pair of ordinaryObject)
//key:value
console.log(pair[0] + ':' + pair[1]);
//or
for (let [key, value] of ordinaryObject)
console.log(key + ':' + value);
So long as you include my shim below:
//makes all objects iterable just like Maps!!! YAY
//iterates over Object.keys() (which already ignores prototype chain for us)
Object.prototype[Symbol.iterator] = function() {
var keys = Object.keys(this)[Symbol.iterator]();
var obj = this;
var output;
return {next:function() {
if (!(output = keys.next()).done)
output.value = [output.value, obj[output.value]];
return output;
}};
};
Without having to create a real Map object that doesn't have the nice syntactic sugar.
var trueMap = new Map([['well', 'hello'], ['there', '!']]);
for (let pair of trueMap)
console.log(pair[0] + ':' + pair[1]);
In fact, with this shim, if you still wanted to take advantage of Map's other functionality (without shimming them all in) but still wanted to use the neat object notation, since objects are now iterable you can now just make a Map from it!
//shown in demo
var realMap = new Map({well:'hello', there:'!'});
For those who don't like to shim, or mess with prototype
in general, feel free to make the function on window instead, calling it something like getObjIterator()
then;
//no prototype manipulation
function getObjIterator(obj) {
//create a dummy object instead of adding functionality to all objects
var iterator = new Object();
//give it what the shim does but as its own local property
iterator[Symbol.iterator] = function() {
var keys = Object.keys(obj)[Symbol.iterator]();
var output;
return {next:function() {
if (!(output = keys.next()).done)
output.value = [output.value, obj[output.value]];
return output;
}};
};
return iterator;
}
Now you can just call it as an ordinary function, nothing else is affected
var realMap = new Map(getObjIterator({well:'hello', there:'!'}))
or
for (let pair of getObjIterator(ordinaryObject))
There's no reason why that wouldn't work.
Welcome to the future.
1
Case in point. So long as people scroll down and find it helpful, that's all that matters. Usually it's me trying to do something, not liking the stuff I see online, end up figuring it out, then I come back to share. It's good doco, I've actually come across my own answers before googling things I completely forgot about!
– Hashbrown
Jul 22 '16 at 6:57
@HelpMeStackOverflowMyOnlyHope Personally I do not like modifying the prototypes of objects I did not define myself.
– Janus Troelsen
Sep 30 '16 at 10:19
@JanusTroelsen did you even read the whole answer?For those who don't like to shim, or mess with prototype in general, feel free to make the function on window instead, calling it something like getObjIterator() then;
– Hashbrown
Sep 30 '16 at 12:58
Note that this technique doesn't work on plain objects, but useful nonetheless.
– noɥʇʎԀʎzɐɹƆ
Jun 14 '18 at 15:17
it does work for plain objects, that's literally the whole point (as well as the variable names likeordinaryObject
for emphasis that the magic still works for those types). Did you check the demos; what isn't working for you, @noɥʇʎԀʎzɐɹƆ? (P.S. your SE profile image is boss)
– Hashbrown
Jun 15 '18 at 6:47
|
show 2 more comments
It's interesting people in these answers have touched on both Object.keys()
and for...of
but never combined them:
var map = {well:'hello', there:'!'};
for (let key of Object.keys(map))
console.log(key + ':' + map[key]);
You can't just for...of
an Object
because it's not an iterator, and for...index
or .forEach()
ing the Object.keys()
is ugly/inefficient.
I'm glad most people are refraining from for...in
(with or without checking .hasOwnProperty()
) as that's also a bit messy, so other than my answer above, I'm here to say...
You can make ordinary object associations iterate! Behaving just like Map
s with direct use of the fancy for...of
DEMO working in Chrome and FF (I assume ES6 only)
var ordinaryObject = {well:'hello', there:'!'};
for (let pair of ordinaryObject)
//key:value
console.log(pair[0] + ':' + pair[1]);
//or
for (let [key, value] of ordinaryObject)
console.log(key + ':' + value);
So long as you include my shim below:
//makes all objects iterable just like Maps!!! YAY
//iterates over Object.keys() (which already ignores prototype chain for us)
Object.prototype[Symbol.iterator] = function() {
var keys = Object.keys(this)[Symbol.iterator]();
var obj = this;
var output;
return {next:function() {
if (!(output = keys.next()).done)
output.value = [output.value, obj[output.value]];
return output;
}};
};
Without having to create a real Map object that doesn't have the nice syntactic sugar.
var trueMap = new Map([['well', 'hello'], ['there', '!']]);
for (let pair of trueMap)
console.log(pair[0] + ':' + pair[1]);
In fact, with this shim, if you still wanted to take advantage of Map's other functionality (without shimming them all in) but still wanted to use the neat object notation, since objects are now iterable you can now just make a Map from it!
//shown in demo
var realMap = new Map({well:'hello', there:'!'});
For those who don't like to shim, or mess with prototype
in general, feel free to make the function on window instead, calling it something like getObjIterator()
then;
//no prototype manipulation
function getObjIterator(obj) {
//create a dummy object instead of adding functionality to all objects
var iterator = new Object();
//give it what the shim does but as its own local property
iterator[Symbol.iterator] = function() {
var keys = Object.keys(obj)[Symbol.iterator]();
var output;
return {next:function() {
if (!(output = keys.next()).done)
output.value = [output.value, obj[output.value]];
return output;
}};
};
return iterator;
}
Now you can just call it as an ordinary function, nothing else is affected
var realMap = new Map(getObjIterator({well:'hello', there:'!'}))
or
for (let pair of getObjIterator(ordinaryObject))
There's no reason why that wouldn't work.
Welcome to the future.
It's interesting people in these answers have touched on both Object.keys()
and for...of
but never combined them:
var map = {well:'hello', there:'!'};
for (let key of Object.keys(map))
console.log(key + ':' + map[key]);
You can't just for...of
an Object
because it's not an iterator, and for...index
or .forEach()
ing the Object.keys()
is ugly/inefficient.
I'm glad most people are refraining from for...in
(with or without checking .hasOwnProperty()
) as that's also a bit messy, so other than my answer above, I'm here to say...
You can make ordinary object associations iterate! Behaving just like Map
s with direct use of the fancy for...of
DEMO working in Chrome and FF (I assume ES6 only)
var ordinaryObject = {well:'hello', there:'!'};
for (let pair of ordinaryObject)
//key:value
console.log(pair[0] + ':' + pair[1]);
//or
for (let [key, value] of ordinaryObject)
console.log(key + ':' + value);
So long as you include my shim below:
//makes all objects iterable just like Maps!!! YAY
//iterates over Object.keys() (which already ignores prototype chain for us)
Object.prototype[Symbol.iterator] = function() {
var keys = Object.keys(this)[Symbol.iterator]();
var obj = this;
var output;
return {next:function() {
if (!(output = keys.next()).done)
output.value = [output.value, obj[output.value]];
return output;
}};
};
Without having to create a real Map object that doesn't have the nice syntactic sugar.
var trueMap = new Map([['well', 'hello'], ['there', '!']]);
for (let pair of trueMap)
console.log(pair[0] + ':' + pair[1]);
In fact, with this shim, if you still wanted to take advantage of Map's other functionality (without shimming them all in) but still wanted to use the neat object notation, since objects are now iterable you can now just make a Map from it!
//shown in demo
var realMap = new Map({well:'hello', there:'!'});
For those who don't like to shim, or mess with prototype
in general, feel free to make the function on window instead, calling it something like getObjIterator()
then;
//no prototype manipulation
function getObjIterator(obj) {
//create a dummy object instead of adding functionality to all objects
var iterator = new Object();
//give it what the shim does but as its own local property
iterator[Symbol.iterator] = function() {
var keys = Object.keys(obj)[Symbol.iterator]();
var output;
return {next:function() {
if (!(output = keys.next()).done)
output.value = [output.value, obj[output.value]];
return output;
}};
};
return iterator;
}
Now you can just call it as an ordinary function, nothing else is affected
var realMap = new Map(getObjIterator({well:'hello', there:'!'}))
or
for (let pair of getObjIterator(ordinaryObject))
There's no reason why that wouldn't work.
Welcome to the future.
edited Jun 16 '18 at 3:28
answered Jun 28 '16 at 9:42
HashbrownHashbrown
5,88764059
5,88764059
1
Case in point. So long as people scroll down and find it helpful, that's all that matters. Usually it's me trying to do something, not liking the stuff I see online, end up figuring it out, then I come back to share. It's good doco, I've actually come across my own answers before googling things I completely forgot about!
– Hashbrown
Jul 22 '16 at 6:57
@HelpMeStackOverflowMyOnlyHope Personally I do not like modifying the prototypes of objects I did not define myself.
– Janus Troelsen
Sep 30 '16 at 10:19
@JanusTroelsen did you even read the whole answer?For those who don't like to shim, or mess with prototype in general, feel free to make the function on window instead, calling it something like getObjIterator() then;
– Hashbrown
Sep 30 '16 at 12:58
Note that this technique doesn't work on plain objects, but useful nonetheless.
– noɥʇʎԀʎzɐɹƆ
Jun 14 '18 at 15:17
it does work for plain objects, that's literally the whole point (as well as the variable names likeordinaryObject
for emphasis that the magic still works for those types). Did you check the demos; what isn't working for you, @noɥʇʎԀʎzɐɹƆ? (P.S. your SE profile image is boss)
– Hashbrown
Jun 15 '18 at 6:47
|
show 2 more comments
1
Case in point. So long as people scroll down and find it helpful, that's all that matters. Usually it's me trying to do something, not liking the stuff I see online, end up figuring it out, then I come back to share. It's good doco, I've actually come across my own answers before googling things I completely forgot about!
– Hashbrown
Jul 22 '16 at 6:57
@HelpMeStackOverflowMyOnlyHope Personally I do not like modifying the prototypes of objects I did not define myself.
– Janus Troelsen
Sep 30 '16 at 10:19
@JanusTroelsen did you even read the whole answer?For those who don't like to shim, or mess with prototype in general, feel free to make the function on window instead, calling it something like getObjIterator() then;
– Hashbrown
Sep 30 '16 at 12:58
Note that this technique doesn't work on plain objects, but useful nonetheless.
– noɥʇʎԀʎzɐɹƆ
Jun 14 '18 at 15:17
it does work for plain objects, that's literally the whole point (as well as the variable names likeordinaryObject
for emphasis that the magic still works for those types). Did you check the demos; what isn't working for you, @noɥʇʎԀʎzɐɹƆ? (P.S. your SE profile image is boss)
– Hashbrown
Jun 15 '18 at 6:47
1
1
Case in point. So long as people scroll down and find it helpful, that's all that matters. Usually it's me trying to do something, not liking the stuff I see online, end up figuring it out, then I come back to share. It's good doco, I've actually come across my own answers before googling things I completely forgot about!
– Hashbrown
Jul 22 '16 at 6:57
Case in point. So long as people scroll down and find it helpful, that's all that matters. Usually it's me trying to do something, not liking the stuff I see online, end up figuring it out, then I come back to share. It's good doco, I've actually come across my own answers before googling things I completely forgot about!
– Hashbrown
Jul 22 '16 at 6:57
@HelpMeStackOverflowMyOnlyHope Personally I do not like modifying the prototypes of objects I did not define myself.
– Janus Troelsen
Sep 30 '16 at 10:19
@HelpMeStackOverflowMyOnlyHope Personally I do not like modifying the prototypes of objects I did not define myself.
– Janus Troelsen
Sep 30 '16 at 10:19
@JanusTroelsen did you even read the whole answer?
For those who don't like to shim, or mess with prototype in general, feel free to make the function on window instead, calling it something like getObjIterator() then;
– Hashbrown
Sep 30 '16 at 12:58
@JanusTroelsen did you even read the whole answer?
For those who don't like to shim, or mess with prototype in general, feel free to make the function on window instead, calling it something like getObjIterator() then;
– Hashbrown
Sep 30 '16 at 12:58
Note that this technique doesn't work on plain objects, but useful nonetheless.
– noɥʇʎԀʎzɐɹƆ
Jun 14 '18 at 15:17
Note that this technique doesn't work on plain objects, but useful nonetheless.
– noɥʇʎԀʎzɐɹƆ
Jun 14 '18 at 15:17
it does work for plain objects, that's literally the whole point (as well as the variable names like
ordinaryObject
for emphasis that the magic still works for those types). Did you check the demos; what isn't working for you, @noɥʇʎԀʎzɐɹƆ? (P.S. your SE profile image is boss)– Hashbrown
Jun 15 '18 at 6:47
it does work for plain objects, that's literally the whole point (as well as the variable names like
ordinaryObject
for emphasis that the magic still works for those types). Did you check the demos; what isn't working for you, @noɥʇʎԀʎzɐɹƆ? (P.S. your SE profile image is boss)– Hashbrown
Jun 15 '18 at 6:47
|
show 2 more comments
Object.keys(obj) : Array
retrieves all string-valued keys of all enumerable own (non-inherited) properties.
So it gives the same list of keys as you intend by testing each object key with hasOwnProperty. You don't need that extra test operation than and Object.keys( obj ).forEach(function( key ){})
is supposed to be faster. Let's prove it:
var uniqid = function(){
var text = "",
i = 0,
possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
for( ; i < 32; i++ ) {
text += possible.charAt( Math.floor( Math.random() * possible.length ) );
}
return text;
},
CYCLES = 100000,
obj = {},
p1,
p2,
p3,
key;
// Populate object with random properties
Array.apply( null, Array( CYCLES ) ).forEach(function(){
obj[ uniqid() ] = new Date()
});
// Approach #1
p1 = performance.now();
Object.keys( obj ).forEach(function( key ){
var waste = obj[ key ];
});
p2 = performance.now();
console.log( "Object.keys approach took " + (p2 - p1) + " milliseconds.");
// Approach #2
for( key in obj ) {
if ( obj.hasOwnProperty( key ) ) {
var waste = obj[ key ];
}
}
p3 = performance.now();
console.log( "for...in/hasOwnProperty approach took " + (p3 - p2) + " milliseconds.");
In my Firefox I have following results
- Object.keys approach took 40.21101451665163 milliseconds.
- for...in/hasOwnProperty approach took 98.26163508463651 milliseconds.
PS. on Chrome the difference even bigger http://codepen.io/dsheiko/pen/JdrqXa
PS2: In ES6 (EcmaScript 2015) you can iterate iterable object nicer:
let map = new Map().set('a', 1).set('b', 2);
for (let pair of map) {
console.log(pair);
}
// OR
let map = new Map([
[false, 'no'],
[true, 'yes'],
]);
map.forEach((value, key) => {
console.log(key, value);
});
if you don't feel like letting go of the {} notation, you can still useof
without creatingMap
s
– Hashbrown
Jun 28 '16 at 9:47
add a comment |
Object.keys(obj) : Array
retrieves all string-valued keys of all enumerable own (non-inherited) properties.
So it gives the same list of keys as you intend by testing each object key with hasOwnProperty. You don't need that extra test operation than and Object.keys( obj ).forEach(function( key ){})
is supposed to be faster. Let's prove it:
var uniqid = function(){
var text = "",
i = 0,
possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
for( ; i < 32; i++ ) {
text += possible.charAt( Math.floor( Math.random() * possible.length ) );
}
return text;
},
CYCLES = 100000,
obj = {},
p1,
p2,
p3,
key;
// Populate object with random properties
Array.apply( null, Array( CYCLES ) ).forEach(function(){
obj[ uniqid() ] = new Date()
});
// Approach #1
p1 = performance.now();
Object.keys( obj ).forEach(function( key ){
var waste = obj[ key ];
});
p2 = performance.now();
console.log( "Object.keys approach took " + (p2 - p1) + " milliseconds.");
// Approach #2
for( key in obj ) {
if ( obj.hasOwnProperty( key ) ) {
var waste = obj[ key ];
}
}
p3 = performance.now();
console.log( "for...in/hasOwnProperty approach took " + (p3 - p2) + " milliseconds.");
In my Firefox I have following results
- Object.keys approach took 40.21101451665163 milliseconds.
- for...in/hasOwnProperty approach took 98.26163508463651 milliseconds.
PS. on Chrome the difference even bigger http://codepen.io/dsheiko/pen/JdrqXa
PS2: In ES6 (EcmaScript 2015) you can iterate iterable object nicer:
let map = new Map().set('a', 1).set('b', 2);
for (let pair of map) {
console.log(pair);
}
// OR
let map = new Map([
[false, 'no'],
[true, 'yes'],
]);
map.forEach((value, key) => {
console.log(key, value);
});
if you don't feel like letting go of the {} notation, you can still useof
without creatingMap
s
– Hashbrown
Jun 28 '16 at 9:47
add a comment |
Object.keys(obj) : Array
retrieves all string-valued keys of all enumerable own (non-inherited) properties.
So it gives the same list of keys as you intend by testing each object key with hasOwnProperty. You don't need that extra test operation than and Object.keys( obj ).forEach(function( key ){})
is supposed to be faster. Let's prove it:
var uniqid = function(){
var text = "",
i = 0,
possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
for( ; i < 32; i++ ) {
text += possible.charAt( Math.floor( Math.random() * possible.length ) );
}
return text;
},
CYCLES = 100000,
obj = {},
p1,
p2,
p3,
key;
// Populate object with random properties
Array.apply( null, Array( CYCLES ) ).forEach(function(){
obj[ uniqid() ] = new Date()
});
// Approach #1
p1 = performance.now();
Object.keys( obj ).forEach(function( key ){
var waste = obj[ key ];
});
p2 = performance.now();
console.log( "Object.keys approach took " + (p2 - p1) + " milliseconds.");
// Approach #2
for( key in obj ) {
if ( obj.hasOwnProperty( key ) ) {
var waste = obj[ key ];
}
}
p3 = performance.now();
console.log( "for...in/hasOwnProperty approach took " + (p3 - p2) + " milliseconds.");
In my Firefox I have following results
- Object.keys approach took 40.21101451665163 milliseconds.
- for...in/hasOwnProperty approach took 98.26163508463651 milliseconds.
PS. on Chrome the difference even bigger http://codepen.io/dsheiko/pen/JdrqXa
PS2: In ES6 (EcmaScript 2015) you can iterate iterable object nicer:
let map = new Map().set('a', 1).set('b', 2);
for (let pair of map) {
console.log(pair);
}
// OR
let map = new Map([
[false, 'no'],
[true, 'yes'],
]);
map.forEach((value, key) => {
console.log(key, value);
});
Object.keys(obj) : Array
retrieves all string-valued keys of all enumerable own (non-inherited) properties.
So it gives the same list of keys as you intend by testing each object key with hasOwnProperty. You don't need that extra test operation than and Object.keys( obj ).forEach(function( key ){})
is supposed to be faster. Let's prove it:
var uniqid = function(){
var text = "",
i = 0,
possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
for( ; i < 32; i++ ) {
text += possible.charAt( Math.floor( Math.random() * possible.length ) );
}
return text;
},
CYCLES = 100000,
obj = {},
p1,
p2,
p3,
key;
// Populate object with random properties
Array.apply( null, Array( CYCLES ) ).forEach(function(){
obj[ uniqid() ] = new Date()
});
// Approach #1
p1 = performance.now();
Object.keys( obj ).forEach(function( key ){
var waste = obj[ key ];
});
p2 = performance.now();
console.log( "Object.keys approach took " + (p2 - p1) + " milliseconds.");
// Approach #2
for( key in obj ) {
if ( obj.hasOwnProperty( key ) ) {
var waste = obj[ key ];
}
}
p3 = performance.now();
console.log( "for...in/hasOwnProperty approach took " + (p3 - p2) + " milliseconds.");
In my Firefox I have following results
- Object.keys approach took 40.21101451665163 milliseconds.
- for...in/hasOwnProperty approach took 98.26163508463651 milliseconds.
PS. on Chrome the difference even bigger http://codepen.io/dsheiko/pen/JdrqXa
PS2: In ES6 (EcmaScript 2015) you can iterate iterable object nicer:
let map = new Map().set('a', 1).set('b', 2);
for (let pair of map) {
console.log(pair);
}
// OR
let map = new Map([
[false, 'no'],
[true, 'yes'],
]);
map.forEach((value, key) => {
console.log(key, value);
});
var uniqid = function(){
var text = "",
i = 0,
possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
for( ; i < 32; i++ ) {
text += possible.charAt( Math.floor( Math.random() * possible.length ) );
}
return text;
},
CYCLES = 100000,
obj = {},
p1,
p2,
p3,
key;
// Populate object with random properties
Array.apply( null, Array( CYCLES ) ).forEach(function(){
obj[ uniqid() ] = new Date()
});
// Approach #1
p1 = performance.now();
Object.keys( obj ).forEach(function( key ){
var waste = obj[ key ];
});
p2 = performance.now();
console.log( "Object.keys approach took " + (p2 - p1) + " milliseconds.");
// Approach #2
for( key in obj ) {
if ( obj.hasOwnProperty( key ) ) {
var waste = obj[ key ];
}
}
p3 = performance.now();
console.log( "for...in/hasOwnProperty approach took " + (p3 - p2) + " milliseconds.");
var uniqid = function(){
var text = "",
i = 0,
possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
for( ; i < 32; i++ ) {
text += possible.charAt( Math.floor( Math.random() * possible.length ) );
}
return text;
},
CYCLES = 100000,
obj = {},
p1,
p2,
p3,
key;
// Populate object with random properties
Array.apply( null, Array( CYCLES ) ).forEach(function(){
obj[ uniqid() ] = new Date()
});
// Approach #1
p1 = performance.now();
Object.keys( obj ).forEach(function( key ){
var waste = obj[ key ];
});
p2 = performance.now();
console.log( "Object.keys approach took " + (p2 - p1) + " milliseconds.");
// Approach #2
for( key in obj ) {
if ( obj.hasOwnProperty( key ) ) {
var waste = obj[ key ];
}
}
p3 = performance.now();
console.log( "for...in/hasOwnProperty approach took " + (p3 - p2) + " milliseconds.");
let map = new Map().set('a', 1).set('b', 2);
for (let pair of map) {
console.log(pair);
}
// OR
let map = new Map([
[false, 'no'],
[true, 'yes'],
]);
map.forEach((value, key) => {
console.log(key, value);
});
let map = new Map().set('a', 1).set('b', 2);
for (let pair of map) {
console.log(pair);
}
// OR
let map = new Map([
[false, 'no'],
[true, 'yes'],
]);
map.forEach((value, key) => {
console.log(key, value);
});
edited Jun 22 '15 at 11:33
answered Jun 22 '15 at 9:52


Dmitry SheikoDmitry Sheiko
1,0721314
1,0721314
if you don't feel like letting go of the {} notation, you can still useof
without creatingMap
s
– Hashbrown
Jun 28 '16 at 9:47
add a comment |
if you don't feel like letting go of the {} notation, you can still useof
without creatingMap
s
– Hashbrown
Jun 28 '16 at 9:47
if you don't feel like letting go of the {} notation, you can still use
of
without creating Map
s– Hashbrown
Jun 28 '16 at 9:47
if you don't feel like letting go of the {} notation, you can still use
of
without creating Map
s– Hashbrown
Jun 28 '16 at 9:47
add a comment |
Here is another method to iterate through an object.
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
Object.keys(p).forEach(key => { console.log(key, p[key]) })
2
This is pretty cool, however for large objects, thefor
method might be more performant.
– Rolf
Mar 10 '18 at 0:17
add a comment |
Here is another method to iterate through an object.
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
Object.keys(p).forEach(key => { console.log(key, p[key]) })
2
This is pretty cool, however for large objects, thefor
method might be more performant.
– Rolf
Mar 10 '18 at 0:17
add a comment |
Here is another method to iterate through an object.
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
Object.keys(p).forEach(key => { console.log(key, p[key]) })
Here is another method to iterate through an object.
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
Object.keys(p).forEach(key => { console.log(key, p[key]) })
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
Object.keys(p).forEach(key => { console.log(key, p[key]) })
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
Object.keys(p).forEach(key => { console.log(key, p[key]) })
answered Dec 20 '17 at 4:42


Harsh PatelHarsh Patel
1,85911332
1,85911332
2
This is pretty cool, however for large objects, thefor
method might be more performant.
– Rolf
Mar 10 '18 at 0:17
add a comment |
2
This is pretty cool, however for large objects, thefor
method might be more performant.
– Rolf
Mar 10 '18 at 0:17
2
2
This is pretty cool, however for large objects, the
for
method might be more performant.– Rolf
Mar 10 '18 at 0:17
This is pretty cool, however for large objects, the
for
method might be more performant.– Rolf
Mar 10 '18 at 0:17
add a comment |
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
for (var key in p) {
if (p.hasOwnProperty(key)) {
console.log(key + " = " + p[key]);
}
}
<p>
Output:<br>
p1 = values1<br>
p2 = values2<br>
p3 = values3
</p>
add a comment |
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
for (var key in p) {
if (p.hasOwnProperty(key)) {
console.log(key + " = " + p[key]);
}
}
<p>
Output:<br>
p1 = values1<br>
p2 = values2<br>
p3 = values3
</p>
add a comment |
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
for (var key in p) {
if (p.hasOwnProperty(key)) {
console.log(key + " = " + p[key]);
}
}
<p>
Output:<br>
p1 = values1<br>
p2 = values2<br>
p3 = values3
</p>
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
for (var key in p) {
if (p.hasOwnProperty(key)) {
console.log(key + " = " + p[key]);
}
}
<p>
Output:<br>
p1 = values1<br>
p2 = values2<br>
p3 = values3
</p>
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
for (var key in p) {
if (p.hasOwnProperty(key)) {
console.log(key + " = " + p[key]);
}
}
<p>
Output:<br>
p1 = values1<br>
p2 = values2<br>
p3 = values3
</p>
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
for (var key in p) {
if (p.hasOwnProperty(key)) {
console.log(key + " = " + p[key]);
}
}
<p>
Output:<br>
p1 = values1<br>
p2 = values2<br>
p3 = values3
</p>
edited Mar 19 '18 at 14:08


TessavWalstijn
799720
799720
answered Feb 21 '12 at 11:22


ParaMeterzParaMeterz
5,11711520
5,11711520
add a comment |
add a comment |
The Object.keys()
method returns an array of a given object's own enumerable properties. Read more about it here
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
Object.keys(p).map((key)=> console.log(key + "->" + p[key]))
1
If you get time, have a look at this: meta.stackexchange.com/q/114762
– Praveen Kumar Purushothaman
Nov 16 '17 at 21:21
add a comment |
The Object.keys()
method returns an array of a given object's own enumerable properties. Read more about it here
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
Object.keys(p).map((key)=> console.log(key + "->" + p[key]))
1
If you get time, have a look at this: meta.stackexchange.com/q/114762
– Praveen Kumar Purushothaman
Nov 16 '17 at 21:21
add a comment |
The Object.keys()
method returns an array of a given object's own enumerable properties. Read more about it here
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
Object.keys(p).map((key)=> console.log(key + "->" + p[key]))
The Object.keys()
method returns an array of a given object's own enumerable properties. Read more about it here
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
Object.keys(p).map((key)=> console.log(key + "->" + p[key]))
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
Object.keys(p).map((key)=> console.log(key + "->" + p[key]))
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
Object.keys(p).map((key)=> console.log(key + "->" + p[key]))
edited Nov 16 '17 at 21:22
answered Nov 16 '17 at 20:04


George BaileyGeorge Bailey
8,0351130
8,0351130
1
If you get time, have a look at this: meta.stackexchange.com/q/114762
– Praveen Kumar Purushothaman
Nov 16 '17 at 21:21
add a comment |
1
If you get time, have a look at this: meta.stackexchange.com/q/114762
– Praveen Kumar Purushothaman
Nov 16 '17 at 21:21
1
1
If you get time, have a look at this: meta.stackexchange.com/q/114762
– Praveen Kumar Purushothaman
Nov 16 '17 at 21:21
If you get time, have a look at this: meta.stackexchange.com/q/114762
– Praveen Kumar Purushothaman
Nov 16 '17 at 21:21
add a comment |
You can add a simple forEach function to all objects, so you can automatically loop through any object:
Object.defineProperty(Object.prototype, 'forEach', {
value: function (func) {
for (var key in this) {
if (!this.hasOwnProperty(key)) {
// skip loop if the property is from prototype
continue;
}
var value = this[key];
func(key, value);
}
},
enumerable: false
});
For those people who don't like the "for ... in"-method:
Object.defineProperty(Object.prototype, 'forEach', {
value: function (func) {
var arr = Object.keys(this);
for (var i = 0; i < arr.length; i++) {
var key = arr[i];
func(key, this[key]);
}
},
enumerable: false
});
Now, you can simple call:
p.forEach (function(key, value){
console.log ("Key: " + key);
console.log ("Value: " + value);
});
If you don't want to get conflicts with other forEach-Methods you can name it with your unique name.
3
Modifying the prototypes of built in objects (likeObject
) is generally considered an anti pattern because it can easily cause conflicts with other code. So wound not recommend doing it this way.
– Moritz
Jan 6 '17 at 13:06
add a comment |
You can add a simple forEach function to all objects, so you can automatically loop through any object:
Object.defineProperty(Object.prototype, 'forEach', {
value: function (func) {
for (var key in this) {
if (!this.hasOwnProperty(key)) {
// skip loop if the property is from prototype
continue;
}
var value = this[key];
func(key, value);
}
},
enumerable: false
});
For those people who don't like the "for ... in"-method:
Object.defineProperty(Object.prototype, 'forEach', {
value: function (func) {
var arr = Object.keys(this);
for (var i = 0; i < arr.length; i++) {
var key = arr[i];
func(key, this[key]);
}
},
enumerable: false
});
Now, you can simple call:
p.forEach (function(key, value){
console.log ("Key: " + key);
console.log ("Value: " + value);
});
If you don't want to get conflicts with other forEach-Methods you can name it with your unique name.
3
Modifying the prototypes of built in objects (likeObject
) is generally considered an anti pattern because it can easily cause conflicts with other code. So wound not recommend doing it this way.
– Moritz
Jan 6 '17 at 13:06
add a comment |
You can add a simple forEach function to all objects, so you can automatically loop through any object:
Object.defineProperty(Object.prototype, 'forEach', {
value: function (func) {
for (var key in this) {
if (!this.hasOwnProperty(key)) {
// skip loop if the property is from prototype
continue;
}
var value = this[key];
func(key, value);
}
},
enumerable: false
});
For those people who don't like the "for ... in"-method:
Object.defineProperty(Object.prototype, 'forEach', {
value: function (func) {
var arr = Object.keys(this);
for (var i = 0; i < arr.length; i++) {
var key = arr[i];
func(key, this[key]);
}
},
enumerable: false
});
Now, you can simple call:
p.forEach (function(key, value){
console.log ("Key: " + key);
console.log ("Value: " + value);
});
If you don't want to get conflicts with other forEach-Methods you can name it with your unique name.
You can add a simple forEach function to all objects, so you can automatically loop through any object:
Object.defineProperty(Object.prototype, 'forEach', {
value: function (func) {
for (var key in this) {
if (!this.hasOwnProperty(key)) {
// skip loop if the property is from prototype
continue;
}
var value = this[key];
func(key, value);
}
},
enumerable: false
});
For those people who don't like the "for ... in"-method:
Object.defineProperty(Object.prototype, 'forEach', {
value: function (func) {
var arr = Object.keys(this);
for (var i = 0; i < arr.length; i++) {
var key = arr[i];
func(key, this[key]);
}
},
enumerable: false
});
Now, you can simple call:
p.forEach (function(key, value){
console.log ("Key: " + key);
console.log ("Value: " + value);
});
If you don't want to get conflicts with other forEach-Methods you can name it with your unique name.
edited Nov 28 '16 at 8:25
answered Nov 22 '16 at 20:46


BiberBiber
585617
585617
3
Modifying the prototypes of built in objects (likeObject
) is generally considered an anti pattern because it can easily cause conflicts with other code. So wound not recommend doing it this way.
– Moritz
Jan 6 '17 at 13:06
add a comment |
3
Modifying the prototypes of built in objects (likeObject
) is generally considered an anti pattern because it can easily cause conflicts with other code. So wound not recommend doing it this way.
– Moritz
Jan 6 '17 at 13:06
3
3
Modifying the prototypes of built in objects (like
Object
) is generally considered an anti pattern because it can easily cause conflicts with other code. So wound not recommend doing it this way.– Moritz
Jan 6 '17 at 13:06
Modifying the prototypes of built in objects (like
Object
) is generally considered an anti pattern because it can easily cause conflicts with other code. So wound not recommend doing it this way.– Moritz
Jan 6 '17 at 13:06
add a comment |
Only JavaScript code without dependencies:
var p = {"p1": "value1", "p2": "value2", "p3": "value3"};
keys = Object.keys(p); // ["p1", "p2", "p3"]
for(i = 0; i < keys.length; i++){
console.log(keys[i] + "=" + p[keys[i]]); // p1=value1, p2=value2, p3=value3
}
add a comment |
Only JavaScript code without dependencies:
var p = {"p1": "value1", "p2": "value2", "p3": "value3"};
keys = Object.keys(p); // ["p1", "p2", "p3"]
for(i = 0; i < keys.length; i++){
console.log(keys[i] + "=" + p[keys[i]]); // p1=value1, p2=value2, p3=value3
}
add a comment |
Only JavaScript code without dependencies:
var p = {"p1": "value1", "p2": "value2", "p3": "value3"};
keys = Object.keys(p); // ["p1", "p2", "p3"]
for(i = 0; i < keys.length; i++){
console.log(keys[i] + "=" + p[keys[i]]); // p1=value1, p2=value2, p3=value3
}
Only JavaScript code without dependencies:
var p = {"p1": "value1", "p2": "value2", "p3": "value3"};
keys = Object.keys(p); // ["p1", "p2", "p3"]
for(i = 0; i < keys.length; i++){
console.log(keys[i] + "=" + p[keys[i]]); // p1=value1, p2=value2, p3=value3
}
edited Jun 16 '16 at 17:34


Peter Mortensen
13.7k1986113
13.7k1986113
answered Apr 21 '15 at 12:02


mohamed-ibrahimmohamed-ibrahim
7,23923141
7,23923141
add a comment |
add a comment |
Loops can be pretty interesting when using pure JavaScript. It seems that only ECMA6 (New 2015 JavaScript specification) got the loops under control. Unfortunately as I'm writing this, both Browsers and popular Integrated development environment (IDE) are still struggling to support completely the new bells and whistles.
At a glance here is what a JavaScript object loop look like before ECMA6:
for (var key in object) {
if (p.hasOwnProperty(key)) {
var value = object[key];
console.log(key); // This is the key;
console.log(value); // This is the value;
}
}
Also, I know this is out of scope with this question but in 2011, ECMAScript 5.1 added the forEach
method for Arrays only which basically created a new improved way to loop through arrays while still leaving non iterable objects with the old verbose and confusing for
loop. But the odd part is that this new forEach
method does not support break
which led to all sorts of other problems.
Basically in 2011, there is not a real solid way to loop in JavaScript other than what many popular libraries (jQuery, Underscore, etc.) decided to re-implement.
As of 2015, we now have a better out of the box way to loop (and break) any object type (including Arrays and Strings). Here is what a loop in JavaScript will eventually look like when the recommendation becomes mainstream:
for (let [key, value] of Object.entries(object)) {
console.log(key); // This is the key;
console.log(value); // This is the value;
}
Note that most browsers won't support the code above as of June 18th 2016. Even in Chrome you need to enable this special flag for it to work: chrome://flags/#enable-javascript-harmony
Until this becomes the new standard, the old method can still be used but there are also alternatives in popular libraries or even lightweight alternatives for those who aren't using any of these libraries.
Could you provide a fiddle of this working? Here is my attempt. jsfiddle.net/abalter/sceeb211
– abalter
Jun 18 '16 at 6:24
@abalter Sorry I realised I had a typo in my code. I fixed it and updated your JsFiddle here: jsfiddle.net/sceeb211/2
– Nicolas Bouvrette
Jun 18 '16 at 12:56
I'm in chrome and gettingUncaught TypeError: Object.entries is not a function
. Is it not implemented in chrome yet?
– abalter
Jun 18 '16 at 16:07
@abalter It is. Make sure you have Chrome version 51 and that you have enabled the flag as explained in my edit and Jsfiddle comments. You can check the details here: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
– Nicolas Bouvrette
Jun 18 '16 at 16:39
Sorry I missed that about the flag. I see it's not a fully implemented feature yet.
– abalter
Jun 19 '16 at 5:39
|
show 3 more comments
Loops can be pretty interesting when using pure JavaScript. It seems that only ECMA6 (New 2015 JavaScript specification) got the loops under control. Unfortunately as I'm writing this, both Browsers and popular Integrated development environment (IDE) are still struggling to support completely the new bells and whistles.
At a glance here is what a JavaScript object loop look like before ECMA6:
for (var key in object) {
if (p.hasOwnProperty(key)) {
var value = object[key];
console.log(key); // This is the key;
console.log(value); // This is the value;
}
}
Also, I know this is out of scope with this question but in 2011, ECMAScript 5.1 added the forEach
method for Arrays only which basically created a new improved way to loop through arrays while still leaving non iterable objects with the old verbose and confusing for
loop. But the odd part is that this new forEach
method does not support break
which led to all sorts of other problems.
Basically in 2011, there is not a real solid way to loop in JavaScript other than what many popular libraries (jQuery, Underscore, etc.) decided to re-implement.
As of 2015, we now have a better out of the box way to loop (and break) any object type (including Arrays and Strings). Here is what a loop in JavaScript will eventually look like when the recommendation becomes mainstream:
for (let [key, value] of Object.entries(object)) {
console.log(key); // This is the key;
console.log(value); // This is the value;
}
Note that most browsers won't support the code above as of June 18th 2016. Even in Chrome you need to enable this special flag for it to work: chrome://flags/#enable-javascript-harmony
Until this becomes the new standard, the old method can still be used but there are also alternatives in popular libraries or even lightweight alternatives for those who aren't using any of these libraries.
Could you provide a fiddle of this working? Here is my attempt. jsfiddle.net/abalter/sceeb211
– abalter
Jun 18 '16 at 6:24
@abalter Sorry I realised I had a typo in my code. I fixed it and updated your JsFiddle here: jsfiddle.net/sceeb211/2
– Nicolas Bouvrette
Jun 18 '16 at 12:56
I'm in chrome and gettingUncaught TypeError: Object.entries is not a function
. Is it not implemented in chrome yet?
– abalter
Jun 18 '16 at 16:07
@abalter It is. Make sure you have Chrome version 51 and that you have enabled the flag as explained in my edit and Jsfiddle comments. You can check the details here: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
– Nicolas Bouvrette
Jun 18 '16 at 16:39
Sorry I missed that about the flag. I see it's not a fully implemented feature yet.
– abalter
Jun 19 '16 at 5:39
|
show 3 more comments
Loops can be pretty interesting when using pure JavaScript. It seems that only ECMA6 (New 2015 JavaScript specification) got the loops under control. Unfortunately as I'm writing this, both Browsers and popular Integrated development environment (IDE) are still struggling to support completely the new bells and whistles.
At a glance here is what a JavaScript object loop look like before ECMA6:
for (var key in object) {
if (p.hasOwnProperty(key)) {
var value = object[key];
console.log(key); // This is the key;
console.log(value); // This is the value;
}
}
Also, I know this is out of scope with this question but in 2011, ECMAScript 5.1 added the forEach
method for Arrays only which basically created a new improved way to loop through arrays while still leaving non iterable objects with the old verbose and confusing for
loop. But the odd part is that this new forEach
method does not support break
which led to all sorts of other problems.
Basically in 2011, there is not a real solid way to loop in JavaScript other than what many popular libraries (jQuery, Underscore, etc.) decided to re-implement.
As of 2015, we now have a better out of the box way to loop (and break) any object type (including Arrays and Strings). Here is what a loop in JavaScript will eventually look like when the recommendation becomes mainstream:
for (let [key, value] of Object.entries(object)) {
console.log(key); // This is the key;
console.log(value); // This is the value;
}
Note that most browsers won't support the code above as of June 18th 2016. Even in Chrome you need to enable this special flag for it to work: chrome://flags/#enable-javascript-harmony
Until this becomes the new standard, the old method can still be used but there are also alternatives in popular libraries or even lightweight alternatives for those who aren't using any of these libraries.
Loops can be pretty interesting when using pure JavaScript. It seems that only ECMA6 (New 2015 JavaScript specification) got the loops under control. Unfortunately as I'm writing this, both Browsers and popular Integrated development environment (IDE) are still struggling to support completely the new bells and whistles.
At a glance here is what a JavaScript object loop look like before ECMA6:
for (var key in object) {
if (p.hasOwnProperty(key)) {
var value = object[key];
console.log(key); // This is the key;
console.log(value); // This is the value;
}
}
Also, I know this is out of scope with this question but in 2011, ECMAScript 5.1 added the forEach
method for Arrays only which basically created a new improved way to loop through arrays while still leaving non iterable objects with the old verbose and confusing for
loop. But the odd part is that this new forEach
method does not support break
which led to all sorts of other problems.
Basically in 2011, there is not a real solid way to loop in JavaScript other than what many popular libraries (jQuery, Underscore, etc.) decided to re-implement.
As of 2015, we now have a better out of the box way to loop (and break) any object type (including Arrays and Strings). Here is what a loop in JavaScript will eventually look like when the recommendation becomes mainstream:
for (let [key, value] of Object.entries(object)) {
console.log(key); // This is the key;
console.log(value); // This is the value;
}
Note that most browsers won't support the code above as of June 18th 2016. Even in Chrome you need to enable this special flag for it to work: chrome://flags/#enable-javascript-harmony
Until this becomes the new standard, the old method can still be used but there are also alternatives in popular libraries or even lightweight alternatives for those who aren't using any of these libraries.
edited Jun 18 '16 at 12:55
answered Jun 18 '16 at 2:11


Nicolas BouvretteNicolas Bouvrette
1,22111029
1,22111029
Could you provide a fiddle of this working? Here is my attempt. jsfiddle.net/abalter/sceeb211
– abalter
Jun 18 '16 at 6:24
@abalter Sorry I realised I had a typo in my code. I fixed it and updated your JsFiddle here: jsfiddle.net/sceeb211/2
– Nicolas Bouvrette
Jun 18 '16 at 12:56
I'm in chrome and gettingUncaught TypeError: Object.entries is not a function
. Is it not implemented in chrome yet?
– abalter
Jun 18 '16 at 16:07
@abalter It is. Make sure you have Chrome version 51 and that you have enabled the flag as explained in my edit and Jsfiddle comments. You can check the details here: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
– Nicolas Bouvrette
Jun 18 '16 at 16:39
Sorry I missed that about the flag. I see it's not a fully implemented feature yet.
– abalter
Jun 19 '16 at 5:39
|
show 3 more comments
Could you provide a fiddle of this working? Here is my attempt. jsfiddle.net/abalter/sceeb211
– abalter
Jun 18 '16 at 6:24
@abalter Sorry I realised I had a typo in my code. I fixed it and updated your JsFiddle here: jsfiddle.net/sceeb211/2
– Nicolas Bouvrette
Jun 18 '16 at 12:56
I'm in chrome and gettingUncaught TypeError: Object.entries is not a function
. Is it not implemented in chrome yet?
– abalter
Jun 18 '16 at 16:07
@abalter It is. Make sure you have Chrome version 51 and that you have enabled the flag as explained in my edit and Jsfiddle comments. You can check the details here: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
– Nicolas Bouvrette
Jun 18 '16 at 16:39
Sorry I missed that about the flag. I see it's not a fully implemented feature yet.
– abalter
Jun 19 '16 at 5:39
Could you provide a fiddle of this working? Here is my attempt. jsfiddle.net/abalter/sceeb211
– abalter
Jun 18 '16 at 6:24
Could you provide a fiddle of this working? Here is my attempt. jsfiddle.net/abalter/sceeb211
– abalter
Jun 18 '16 at 6:24
@abalter Sorry I realised I had a typo in my code. I fixed it and updated your JsFiddle here: jsfiddle.net/sceeb211/2
– Nicolas Bouvrette
Jun 18 '16 at 12:56
@abalter Sorry I realised I had a typo in my code. I fixed it and updated your JsFiddle here: jsfiddle.net/sceeb211/2
– Nicolas Bouvrette
Jun 18 '16 at 12:56
I'm in chrome and getting
Uncaught TypeError: Object.entries is not a function
. Is it not implemented in chrome yet?– abalter
Jun 18 '16 at 16:07
I'm in chrome and getting
Uncaught TypeError: Object.entries is not a function
. Is it not implemented in chrome yet?– abalter
Jun 18 '16 at 16:07
@abalter It is. Make sure you have Chrome version 51 and that you have enabled the flag as explained in my edit and Jsfiddle comments. You can check the details here: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
– Nicolas Bouvrette
Jun 18 '16 at 16:39
@abalter It is. Make sure you have Chrome version 51 and that you have enabled the flag as explained in my edit and Jsfiddle comments. You can check the details here: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
– Nicolas Bouvrette
Jun 18 '16 at 16:39
Sorry I missed that about the flag. I see it's not a fully implemented feature yet.
– abalter
Jun 19 '16 at 5:39
Sorry I missed that about the flag. I see it's not a fully implemented feature yet.
– abalter
Jun 19 '16 at 5:39
|
show 3 more comments
I would do this rather than checking obj.hasOwnerProperty
within every for ... in
loop.
var obj = {a : 1};
for(var key in obj){
//obj.hasOwnProperty(key) is not needed.
console.log(key);
}
//then check if anybody has messed the native object. Put this code at the end of the page.
for(var key in Object){
throw new Error("Please don't extend the native object");
}
add a comment |
I would do this rather than checking obj.hasOwnerProperty
within every for ... in
loop.
var obj = {a : 1};
for(var key in obj){
//obj.hasOwnProperty(key) is not needed.
console.log(key);
}
//then check if anybody has messed the native object. Put this code at the end of the page.
for(var key in Object){
throw new Error("Please don't extend the native object");
}
add a comment |
I would do this rather than checking obj.hasOwnerProperty
within every for ... in
loop.
var obj = {a : 1};
for(var key in obj){
//obj.hasOwnProperty(key) is not needed.
console.log(key);
}
//then check if anybody has messed the native object. Put this code at the end of the page.
for(var key in Object){
throw new Error("Please don't extend the native object");
}
I would do this rather than checking obj.hasOwnerProperty
within every for ... in
loop.
var obj = {a : 1};
for(var key in obj){
//obj.hasOwnProperty(key) is not needed.
console.log(key);
}
//then check if anybody has messed the native object. Put this code at the end of the page.
for(var key in Object){
throw new Error("Please don't extend the native object");
}
edited Nov 10 '16 at 10:04
answered Jul 9 '15 at 8:22


LewisLewis
7,94774565
7,94774565
add a comment |
add a comment |
If you want to iterate over non-enumerable properties as well, you can use Object.getOwnPropertyNames(obj)
to return an array of all properties (enumerable or not) found directly upon a given object.
var obj = Object.create({}, {
// non-enumerable property
getFoo: {
value: function() { return this.foo; },
enumerable: false
}
});
obj.foo = 1; // enumerable property
Object.getOwnPropertyNames(obj).forEach(function (name) {
document.write(name + ': ' + obj[name] + '<br/>');
});
2
This is fantastic, thank you for posting this answer. I needed to introspect anError
object and couldn't get at the properties in a loop or a_.forIn(err)
call. UsingObject.getOwnPropertyNames(err)
allowed me to access all the parts of theError
that I couldn't get at before. Thanks!
– Pierce
Mar 11 '16 at 19:49
add a comment |
If you want to iterate over non-enumerable properties as well, you can use Object.getOwnPropertyNames(obj)
to return an array of all properties (enumerable or not) found directly upon a given object.
var obj = Object.create({}, {
// non-enumerable property
getFoo: {
value: function() { return this.foo; },
enumerable: false
}
});
obj.foo = 1; // enumerable property
Object.getOwnPropertyNames(obj).forEach(function (name) {
document.write(name + ': ' + obj[name] + '<br/>');
});
2
This is fantastic, thank you for posting this answer. I needed to introspect anError
object and couldn't get at the properties in a loop or a_.forIn(err)
call. UsingObject.getOwnPropertyNames(err)
allowed me to access all the parts of theError
that I couldn't get at before. Thanks!
– Pierce
Mar 11 '16 at 19:49
add a comment |
If you want to iterate over non-enumerable properties as well, you can use Object.getOwnPropertyNames(obj)
to return an array of all properties (enumerable or not) found directly upon a given object.
var obj = Object.create({}, {
// non-enumerable property
getFoo: {
value: function() { return this.foo; },
enumerable: false
}
});
obj.foo = 1; // enumerable property
Object.getOwnPropertyNames(obj).forEach(function (name) {
document.write(name + ': ' + obj[name] + '<br/>');
});
If you want to iterate over non-enumerable properties as well, you can use Object.getOwnPropertyNames(obj)
to return an array of all properties (enumerable or not) found directly upon a given object.
var obj = Object.create({}, {
// non-enumerable property
getFoo: {
value: function() { return this.foo; },
enumerable: false
}
});
obj.foo = 1; // enumerable property
Object.getOwnPropertyNames(obj).forEach(function (name) {
document.write(name + ': ' + obj[name] + '<br/>');
});
var obj = Object.create({}, {
// non-enumerable property
getFoo: {
value: function() { return this.foo; },
enumerable: false
}
});
obj.foo = 1; // enumerable property
Object.getOwnPropertyNames(obj).forEach(function (name) {
document.write(name + ': ' + obj[name] + '<br/>');
});
var obj = Object.create({}, {
// non-enumerable property
getFoo: {
value: function() { return this.foo; },
enumerable: false
}
});
obj.foo = 1; // enumerable property
Object.getOwnPropertyNames(obj).forEach(function (name) {
document.write(name + ': ' + obj[name] + '<br/>');
});
edited Nov 11 '15 at 5:26
answered Sep 12 '15 at 16:31
Dheeraj V.S.Dheeraj V.S.
13.9k75488
13.9k75488
2
This is fantastic, thank you for posting this answer. I needed to introspect anError
object and couldn't get at the properties in a loop or a_.forIn(err)
call. UsingObject.getOwnPropertyNames(err)
allowed me to access all the parts of theError
that I couldn't get at before. Thanks!
– Pierce
Mar 11 '16 at 19:49
add a comment |
2
This is fantastic, thank you for posting this answer. I needed to introspect anError
object and couldn't get at the properties in a loop or a_.forIn(err)
call. UsingObject.getOwnPropertyNames(err)
allowed me to access all the parts of theError
that I couldn't get at before. Thanks!
– Pierce
Mar 11 '16 at 19:49
2
2
This is fantastic, thank you for posting this answer. I needed to introspect an
Error
object and couldn't get at the properties in a loop or a _.forIn(err)
call. Using Object.getOwnPropertyNames(err)
allowed me to access all the parts of the Error
that I couldn't get at before. Thanks!– Pierce
Mar 11 '16 at 19:49
This is fantastic, thank you for posting this answer. I needed to introspect an
Error
object and couldn't get at the properties in a loop or a _.forIn(err)
call. Using Object.getOwnPropertyNames(err)
allowed me to access all the parts of the Error
that I couldn't get at before. Thanks!– Pierce
Mar 11 '16 at 19:49
add a comment |
If anybody needs to loop through arrayObjects with condition:
var arrayObjects = [{"building":"A", "status":"good"},{"building":"B","status":"horrible"}];
for (var i=0; i< arrayObjects.length; i++) {
console.log(arrayObjects[i]);
for(key in arrayObjects[i]) {
if (key == "status" && arrayObjects[i][key] == "good") {
console.log(key + "->" + arrayObjects[i][key]);
}else{
console.log("nothing found");
}
}
}
add a comment |
If anybody needs to loop through arrayObjects with condition:
var arrayObjects = [{"building":"A", "status":"good"},{"building":"B","status":"horrible"}];
for (var i=0; i< arrayObjects.length; i++) {
console.log(arrayObjects[i]);
for(key in arrayObjects[i]) {
if (key == "status" && arrayObjects[i][key] == "good") {
console.log(key + "->" + arrayObjects[i][key]);
}else{
console.log("nothing found");
}
}
}
add a comment |
If anybody needs to loop through arrayObjects with condition:
var arrayObjects = [{"building":"A", "status":"good"},{"building":"B","status":"horrible"}];
for (var i=0; i< arrayObjects.length; i++) {
console.log(arrayObjects[i]);
for(key in arrayObjects[i]) {
if (key == "status" && arrayObjects[i][key] == "good") {
console.log(key + "->" + arrayObjects[i][key]);
}else{
console.log("nothing found");
}
}
}
If anybody needs to loop through arrayObjects with condition:
var arrayObjects = [{"building":"A", "status":"good"},{"building":"B","status":"horrible"}];
for (var i=0; i< arrayObjects.length; i++) {
console.log(arrayObjects[i]);
for(key in arrayObjects[i]) {
if (key == "status" && arrayObjects[i][key] == "good") {
console.log(key + "->" + arrayObjects[i][key]);
}else{
console.log("nothing found");
}
}
}
var arrayObjects = [{"building":"A", "status":"good"},{"building":"B","status":"horrible"}];
for (var i=0; i< arrayObjects.length; i++) {
console.log(arrayObjects[i]);
for(key in arrayObjects[i]) {
if (key == "status" && arrayObjects[i][key] == "good") {
console.log(key + "->" + arrayObjects[i][key]);
}else{
console.log("nothing found");
}
}
}
var arrayObjects = [{"building":"A", "status":"good"},{"building":"B","status":"horrible"}];
for (var i=0; i< arrayObjects.length; i++) {
console.log(arrayObjects[i]);
for(key in arrayObjects[i]) {
if (key == "status" && arrayObjects[i][key] == "good") {
console.log(key + "->" + arrayObjects[i][key]);
}else{
console.log("nothing found");
}
}
}
answered Jul 22 '16 at 3:48
Tadas V.Tadas V.
3251415
3251415
add a comment |
add a comment |
Considering ES6 I'd like to add my own spoon of sugar and provide one more approach to iterate over object's properties.
Since plain JS object isn't iterable just out of box, we aren't able to use for..of
loop for iterating over its content. But no one can stop us to make it iterable.
Let's we have book
object.
let book = {
title: "Amazing book",
author: "Me",
pages: 3
}
book[Symbol.iterator] = function(){
let properties = Object.keys(this); // returns an array with property names
let counter = 0;
let isDone = false;
let next = () => {
if(counter >= properties.length){
isDone = true;
}
return { done: isDone, value: this[properties[counter++]] }
}
return { next };
}
Since we've made it we can use it this way:
for(let pValue of book){
console.log(pValue);
}
------------------------
Amazing book
Me
3
Or if you know the power of ES6 generators, so you certainly can make the code above much shorter.
book[Symbol.iterator] = function *(){
let properties = Object.keys(this);
for (let p of properties){
yield this[p];
}
}
Sure, you can apply such behavior for all objects with making Object
iterable on prototype
level.
Object.prototype[Symbol.iterator] = function() {...}
Also, objects that comply with the iterable protocol can be used with the new ES2015 feature spread operator thus we can read object property values as an array.
let pValues = [...book];
console.log(pValues);
-------------------------
["Amazing book", "Me", 3]
Or you can use destructuring assignment:
let [title, , pages] = book; // notice that we can just skip unnecessary values
console.log(title);
console.log(pages);
------------------
Amazing book
3
You can check out JSFiddle with all code I've provided above.
I found the code will generate the values but without keys. Is it possible to iterate the values with keys?
– Pika
Sep 8 '16 at 3:34
Yes, you can. Just return "yield [key, obj[key]];" from your generator function and then use it like the following "for(let [ key, value ] of {}) { }"
– Artyom Pranovich
Sep 8 '16 at 13:33
add a comment |
Considering ES6 I'd like to add my own spoon of sugar and provide one more approach to iterate over object's properties.
Since plain JS object isn't iterable just out of box, we aren't able to use for..of
loop for iterating over its content. But no one can stop us to make it iterable.
Let's we have book
object.
let book = {
title: "Amazing book",
author: "Me",
pages: 3
}
book[Symbol.iterator] = function(){
let properties = Object.keys(this); // returns an array with property names
let counter = 0;
let isDone = false;
let next = () => {
if(counter >= properties.length){
isDone = true;
}
return { done: isDone, value: this[properties[counter++]] }
}
return { next };
}
Since we've made it we can use it this way:
for(let pValue of book){
console.log(pValue);
}
------------------------
Amazing book
Me
3
Or if you know the power of ES6 generators, so you certainly can make the code above much shorter.
book[Symbol.iterator] = function *(){
let properties = Object.keys(this);
for (let p of properties){
yield this[p];
}
}
Sure, you can apply such behavior for all objects with making Object
iterable on prototype
level.
Object.prototype[Symbol.iterator] = function() {...}
Also, objects that comply with the iterable protocol can be used with the new ES2015 feature spread operator thus we can read object property values as an array.
let pValues = [...book];
console.log(pValues);
-------------------------
["Amazing book", "Me", 3]
Or you can use destructuring assignment:
let [title, , pages] = book; // notice that we can just skip unnecessary values
console.log(title);
console.log(pages);
------------------
Amazing book
3
You can check out JSFiddle with all code I've provided above.
I found the code will generate the values but without keys. Is it possible to iterate the values with keys?
– Pika
Sep 8 '16 at 3:34
Yes, you can. Just return "yield [key, obj[key]];" from your generator function and then use it like the following "for(let [ key, value ] of {}) { }"
– Artyom Pranovich
Sep 8 '16 at 13:33
add a comment |
Considering ES6 I'd like to add my own spoon of sugar and provide one more approach to iterate over object's properties.
Since plain JS object isn't iterable just out of box, we aren't able to use for..of
loop for iterating over its content. But no one can stop us to make it iterable.
Let's we have book
object.
let book = {
title: "Amazing book",
author: "Me",
pages: 3
}
book[Symbol.iterator] = function(){
let properties = Object.keys(this); // returns an array with property names
let counter = 0;
let isDone = false;
let next = () => {
if(counter >= properties.length){
isDone = true;
}
return { done: isDone, value: this[properties[counter++]] }
}
return { next };
}
Since we've made it we can use it this way:
for(let pValue of book){
console.log(pValue);
}
------------------------
Amazing book
Me
3
Or if you know the power of ES6 generators, so you certainly can make the code above much shorter.
book[Symbol.iterator] = function *(){
let properties = Object.keys(this);
for (let p of properties){
yield this[p];
}
}
Sure, you can apply such behavior for all objects with making Object
iterable on prototype
level.
Object.prototype[Symbol.iterator] = function() {...}
Also, objects that comply with the iterable protocol can be used with the new ES2015 feature spread operator thus we can read object property values as an array.
let pValues = [...book];
console.log(pValues);
-------------------------
["Amazing book", "Me", 3]
Or you can use destructuring assignment:
let [title, , pages] = book; // notice that we can just skip unnecessary values
console.log(title);
console.log(pages);
------------------
Amazing book
3
You can check out JSFiddle with all code I've provided above.
Considering ES6 I'd like to add my own spoon of sugar and provide one more approach to iterate over object's properties.
Since plain JS object isn't iterable just out of box, we aren't able to use for..of
loop for iterating over its content. But no one can stop us to make it iterable.
Let's we have book
object.
let book = {
title: "Amazing book",
author: "Me",
pages: 3
}
book[Symbol.iterator] = function(){
let properties = Object.keys(this); // returns an array with property names
let counter = 0;
let isDone = false;
let next = () => {
if(counter >= properties.length){
isDone = true;
}
return { done: isDone, value: this[properties[counter++]] }
}
return { next };
}
Since we've made it we can use it this way:
for(let pValue of book){
console.log(pValue);
}
------------------------
Amazing book
Me
3
Or if you know the power of ES6 generators, so you certainly can make the code above much shorter.
book[Symbol.iterator] = function *(){
let properties = Object.keys(this);
for (let p of properties){
yield this[p];
}
}
Sure, you can apply such behavior for all objects with making Object
iterable on prototype
level.
Object.prototype[Symbol.iterator] = function() {...}
Also, objects that comply with the iterable protocol can be used with the new ES2015 feature spread operator thus we can read object property values as an array.
let pValues = [...book];
console.log(pValues);
-------------------------
["Amazing book", "Me", 3]
Or you can use destructuring assignment:
let [title, , pages] = book; // notice that we can just skip unnecessary values
console.log(title);
console.log(pages);
------------------
Amazing book
3
You can check out JSFiddle with all code I've provided above.
edited Sep 2 '16 at 13:56
answered Sep 1 '16 at 20:15
Artyom PranovichArtyom Pranovich
4,89432649
4,89432649
I found the code will generate the values but without keys. Is it possible to iterate the values with keys?
– Pika
Sep 8 '16 at 3:34
Yes, you can. Just return "yield [key, obj[key]];" from your generator function and then use it like the following "for(let [ key, value ] of {}) { }"
– Artyom Pranovich
Sep 8 '16 at 13:33
add a comment |
I found the code will generate the values but without keys. Is it possible to iterate the values with keys?
– Pika
Sep 8 '16 at 3:34
Yes, you can. Just return "yield [key, obj[key]];" from your generator function and then use it like the following "for(let [ key, value ] of {}) { }"
– Artyom Pranovich
Sep 8 '16 at 13:33
I found the code will generate the values but without keys. Is it possible to iterate the values with keys?
– Pika
Sep 8 '16 at 3:34
I found the code will generate the values but without keys. Is it possible to iterate the values with keys?
– Pika
Sep 8 '16 at 3:34
Yes, you can. Just return "yield [key, obj[key]];" from your generator function and then use it like the following "for(let [ key, value ] of {}) { }"
– Artyom Pranovich
Sep 8 '16 at 13:33
Yes, you can. Just return "yield [key, obj[key]];" from your generator function and then use it like the following "for(let [ key, value ] of {}) { }"
– Artyom Pranovich
Sep 8 '16 at 13:33
add a comment |
In latest ES script, you can do something like this:
Object.entries(p);
add a comment |
In latest ES script, you can do something like this:
Object.entries(p);
add a comment |
In latest ES script, you can do something like this:
Object.entries(p);
In latest ES script, you can do something like this:
Object.entries(p);
answered Sep 11 '18 at 5:55
AnkitAnkit
66329
66329
add a comment |
add a comment |
var p =[{"username":"ordermanageadmin","user_id":"2","resource_id":"Magento_Sales::actions"},
{"username":"ordermanageadmin_1","user_id":"3","resource_id":"Magento_Sales::actions"}]
for(var value in p) {
for (var key in value) {
if (p.hasOwnProperty(key)) {
console.log(key + " -> " + p[key]);
}
}
}
json = [{"key1":"value1","key2":"value2"},{"key1":"value3","key2":"value4"}] for (var i = 0; i < json.length; i++) { for (var key in json[i]) { if (json[i].hasOwnProperty(key)) { console.log(key + " -> " + json[i][key]); } } }
– Marek Bernád
Oct 14 '18 at 12:27
add a comment |
var p =[{"username":"ordermanageadmin","user_id":"2","resource_id":"Magento_Sales::actions"},
{"username":"ordermanageadmin_1","user_id":"3","resource_id":"Magento_Sales::actions"}]
for(var value in p) {
for (var key in value) {
if (p.hasOwnProperty(key)) {
console.log(key + " -> " + p[key]);
}
}
}
json = [{"key1":"value1","key2":"value2"},{"key1":"value3","key2":"value4"}] for (var i = 0; i < json.length; i++) { for (var key in json[i]) { if (json[i].hasOwnProperty(key)) { console.log(key + " -> " + json[i][key]); } } }
– Marek Bernád
Oct 14 '18 at 12:27
add a comment |
var p =[{"username":"ordermanageadmin","user_id":"2","resource_id":"Magento_Sales::actions"},
{"username":"ordermanageadmin_1","user_id":"3","resource_id":"Magento_Sales::actions"}]
for(var value in p) {
for (var key in value) {
if (p.hasOwnProperty(key)) {
console.log(key + " -> " + p[key]);
}
}
}
var p =[{"username":"ordermanageadmin","user_id":"2","resource_id":"Magento_Sales::actions"},
{"username":"ordermanageadmin_1","user_id":"3","resource_id":"Magento_Sales::actions"}]
for(var value in p) {
for (var key in value) {
if (p.hasOwnProperty(key)) {
console.log(key + " -> " + p[key]);
}
}
}
var p =[{"username":"ordermanageadmin","user_id":"2","resource_id":"Magento_Sales::actions"},
{"username":"ordermanageadmin_1","user_id":"3","resource_id":"Magento_Sales::actions"}]
for(var value in p) {
for (var key in value) {
if (p.hasOwnProperty(key)) {
console.log(key + " -> " + p[key]);
}
}
}
var p =[{"username":"ordermanageadmin","user_id":"2","resource_id":"Magento_Sales::actions"},
{"username":"ordermanageadmin_1","user_id":"3","resource_id":"Magento_Sales::actions"}]
for(var value in p) {
for (var key in value) {
if (p.hasOwnProperty(key)) {
console.log(key + " -> " + p[key]);
}
}
}
edited Sep 14 '18 at 17:51


Zakaria Acharki
55.7k134370
55.7k134370
answered Jun 26 '18 at 14:34


senthilsenthil
240111
240111
json = [{"key1":"value1","key2":"value2"},{"key1":"value3","key2":"value4"}] for (var i = 0; i < json.length; i++) { for (var key in json[i]) { if (json[i].hasOwnProperty(key)) { console.log(key + " -> " + json[i][key]); } } }
– Marek Bernád
Oct 14 '18 at 12:27
add a comment |
json = [{"key1":"value1","key2":"value2"},{"key1":"value3","key2":"value4"}] for (var i = 0; i < json.length; i++) { for (var key in json[i]) { if (json[i].hasOwnProperty(key)) { console.log(key + " -> " + json[i][key]); } } }
– Marek Bernád
Oct 14 '18 at 12:27
json = [{"key1":"value1","key2":"value2"},{"key1":"value3","key2":"value4"}] for (var i = 0; i < json.length; i++) { for (var key in json[i]) { if (json[i].hasOwnProperty(key)) { console.log(key + " -> " + json[i][key]); } } }
– Marek Bernád
Oct 14 '18 at 12:27
json = [{"key1":"value1","key2":"value2"},{"key1":"value3","key2":"value4"}] for (var i = 0; i < json.length; i++) { for (var key in json[i]) { if (json[i].hasOwnProperty(key)) { console.log(key + " -> " + json[i][key]); } } }
– Marek Bernád
Oct 14 '18 at 12:27
add a comment |
In ES6 we have well-known symbols to expose some previously internal methods, you can use it to define how iterators work for this object:
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3",
*[Symbol.iterator]() {
yield *Object.keys(this);
}
};
[...p] //["p1", "p2", "p3"]
this will give the same result as using for...in es6 loop.
for(var key in p) {
console.log(key);
}
But its important to know the capabilities you now have using es6!
add a comment |
In ES6 we have well-known symbols to expose some previously internal methods, you can use it to define how iterators work for this object:
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3",
*[Symbol.iterator]() {
yield *Object.keys(this);
}
};
[...p] //["p1", "p2", "p3"]
this will give the same result as using for...in es6 loop.
for(var key in p) {
console.log(key);
}
But its important to know the capabilities you now have using es6!
add a comment |
In ES6 we have well-known symbols to expose some previously internal methods, you can use it to define how iterators work for this object:
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3",
*[Symbol.iterator]() {
yield *Object.keys(this);
}
};
[...p] //["p1", "p2", "p3"]
this will give the same result as using for...in es6 loop.
for(var key in p) {
console.log(key);
}
But its important to know the capabilities you now have using es6!
In ES6 we have well-known symbols to expose some previously internal methods, you can use it to define how iterators work for this object:
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3",
*[Symbol.iterator]() {
yield *Object.keys(this);
}
};
[...p] //["p1", "p2", "p3"]
this will give the same result as using for...in es6 loop.
for(var key in p) {
console.log(key);
}
But its important to know the capabilities you now have using es6!
answered Sep 20 '16 at 9:04
BamiehBamieh
4,96321438
4,96321438
add a comment |
add a comment |
An object becomes an iterator when it implements the .next() method
const james = {
name: 'James',
height: `5'10"`,
weight: 185,
[Symbol.iterator]() {
let properties =
for (let key of Object.keys(james)){
properties.push(key);
}
index = 0;
return {
next: () => {
let key = properties[index];
let value = this[key];
let done = index >= properties.length - 1 ;
index++;
return { key, value, done };
}
};
}
};
const iterator = james[Symbol.iterator]();
console.log(iterator.next().value); // 'James'
console.log(iterator.next().value); // `5'10`
console.log(iterator.next().value); // 185
add a comment |
An object becomes an iterator when it implements the .next() method
const james = {
name: 'James',
height: `5'10"`,
weight: 185,
[Symbol.iterator]() {
let properties =
for (let key of Object.keys(james)){
properties.push(key);
}
index = 0;
return {
next: () => {
let key = properties[index];
let value = this[key];
let done = index >= properties.length - 1 ;
index++;
return { key, value, done };
}
};
}
};
const iterator = james[Symbol.iterator]();
console.log(iterator.next().value); // 'James'
console.log(iterator.next().value); // `5'10`
console.log(iterator.next().value); // 185
add a comment |
An object becomes an iterator when it implements the .next() method
const james = {
name: 'James',
height: `5'10"`,
weight: 185,
[Symbol.iterator]() {
let properties =
for (let key of Object.keys(james)){
properties.push(key);
}
index = 0;
return {
next: () => {
let key = properties[index];
let value = this[key];
let done = index >= properties.length - 1 ;
index++;
return { key, value, done };
}
};
}
};
const iterator = james[Symbol.iterator]();
console.log(iterator.next().value); // 'James'
console.log(iterator.next().value); // `5'10`
console.log(iterator.next().value); // 185
An object becomes an iterator when it implements the .next() method
const james = {
name: 'James',
height: `5'10"`,
weight: 185,
[Symbol.iterator]() {
let properties =
for (let key of Object.keys(james)){
properties.push(key);
}
index = 0;
return {
next: () => {
let key = properties[index];
let value = this[key];
let done = index >= properties.length - 1 ;
index++;
return { key, value, done };
}
};
}
};
const iterator = james[Symbol.iterator]();
console.log(iterator.next().value); // 'James'
console.log(iterator.next().value); // `5'10`
console.log(iterator.next().value); // 185
answered Nov 13 '17 at 16:05


Dan AlboteanuDan Alboteanu
2,2671616
2,2671616
add a comment |
add a comment |
since ES06 you can get the values of an object as array with
let arrValues = Object.values( yourObject) ;
it return the an array of the object values and it not extract values from Prototype!!
MDN DOCS Object.values()
and for keys ( allready answerd before me here )
let arrKeys = Object.keys(yourObject);
The answers asks for a solution that returns both keys and values.
– Sean Lindo
Aug 21 '18 at 19:03
pepole allready answer for that. i add it now for you
– yehonatan yehezkel
Aug 22 '18 at 15:42
add a comment |
since ES06 you can get the values of an object as array with
let arrValues = Object.values( yourObject) ;
it return the an array of the object values and it not extract values from Prototype!!
MDN DOCS Object.values()
and for keys ( allready answerd before me here )
let arrKeys = Object.keys(yourObject);
The answers asks for a solution that returns both keys and values.
– Sean Lindo
Aug 21 '18 at 19:03
pepole allready answer for that. i add it now for you
– yehonatan yehezkel
Aug 22 '18 at 15:42
add a comment |
since ES06 you can get the values of an object as array with
let arrValues = Object.values( yourObject) ;
it return the an array of the object values and it not extract values from Prototype!!
MDN DOCS Object.values()
and for keys ( allready answerd before me here )
let arrKeys = Object.keys(yourObject);
since ES06 you can get the values of an object as array with
let arrValues = Object.values( yourObject) ;
it return the an array of the object values and it not extract values from Prototype!!
MDN DOCS Object.values()
and for keys ( allready answerd before me here )
let arrKeys = Object.keys(yourObject);
edited Aug 22 '18 at 15:41
answered Jul 9 '18 at 16:15
yehonatan yehezkelyehonatan yehezkel
404513
404513
The answers asks for a solution that returns both keys and values.
– Sean Lindo
Aug 21 '18 at 19:03
pepole allready answer for that. i add it now for you
– yehonatan yehezkel
Aug 22 '18 at 15:42
add a comment |
The answers asks for a solution that returns both keys and values.
– Sean Lindo
Aug 21 '18 at 19:03
pepole allready answer for that. i add it now for you
– yehonatan yehezkel
Aug 22 '18 at 15:42
The answers asks for a solution that returns both keys and values.
– Sean Lindo
Aug 21 '18 at 19:03
The answers asks for a solution that returns both keys and values.
– Sean Lindo
Aug 21 '18 at 19:03
pepole allready answer for that. i add it now for you
– yehonatan yehezkel
Aug 22 '18 at 15:42
pepole allready answer for that. i add it now for you
– yehonatan yehezkel
Aug 22 '18 at 15:42
add a comment |
If you want to iterate only over properties use one of the answers above, however if you want to iterate over everything including functions, then you might want to use Object.getOwnPropertyNames(obj)
for (let o of Object.getOwnPropertyNames(Math)) {
console.log(o);
}
I sometimes use this to fast test all functions on objects with simple inputs and outputs.
add a comment |
If you want to iterate only over properties use one of the answers above, however if you want to iterate over everything including functions, then you might want to use Object.getOwnPropertyNames(obj)
for (let o of Object.getOwnPropertyNames(Math)) {
console.log(o);
}
I sometimes use this to fast test all functions on objects with simple inputs and outputs.
add a comment |
If you want to iterate only over properties use one of the answers above, however if you want to iterate over everything including functions, then you might want to use Object.getOwnPropertyNames(obj)
for (let o of Object.getOwnPropertyNames(Math)) {
console.log(o);
}
I sometimes use this to fast test all functions on objects with simple inputs and outputs.
If you want to iterate only over properties use one of the answers above, however if you want to iterate over everything including functions, then you might want to use Object.getOwnPropertyNames(obj)
for (let o of Object.getOwnPropertyNames(Math)) {
console.log(o);
}
I sometimes use this to fast test all functions on objects with simple inputs and outputs.
for (let o of Object.getOwnPropertyNames(Math)) {
console.log(o);
}
for (let o of Object.getOwnPropertyNames(Math)) {
console.log(o);
}
answered Feb 7 '18 at 11:22
Matas VaitkeviciusMatas Vaitkevicius
33.8k15165176
33.8k15165176
add a comment |
add a comment |
Object.entries()
function:
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
for (var i in Object.entries(p)){
var key = Object.entries(p)[i][0];
var value = Object.entries(p)[i][1];
console.log('key['+i+']='+key+' '+'value['+i+']='+value);
}
please don't remove the snippet if you edit my entry
– nrb
Oct 29 '18 at 19:22
add a comment |
Object.entries()
function:
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
for (var i in Object.entries(p)){
var key = Object.entries(p)[i][0];
var value = Object.entries(p)[i][1];
console.log('key['+i+']='+key+' '+'value['+i+']='+value);
}
please don't remove the snippet if you edit my entry
– nrb
Oct 29 '18 at 19:22
add a comment |
Object.entries()
function:
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
for (var i in Object.entries(p)){
var key = Object.entries(p)[i][0];
var value = Object.entries(p)[i][1];
console.log('key['+i+']='+key+' '+'value['+i+']='+value);
}
Object.entries()
function:
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
for (var i in Object.entries(p)){
var key = Object.entries(p)[i][0];
var value = Object.entries(p)[i][1];
console.log('key['+i+']='+key+' '+'value['+i+']='+value);
}
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
for (var i in Object.entries(p)){
var key = Object.entries(p)[i][0];
var value = Object.entries(p)[i][1];
console.log('key['+i+']='+key+' '+'value['+i+']='+value);
}
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
for (var i in Object.entries(p)){
var key = Object.entries(p)[i][0];
var value = Object.entries(p)[i][1];
console.log('key['+i+']='+key+' '+'value['+i+']='+value);
}
edited Oct 29 '18 at 19:21
answered Oct 24 '18 at 19:51
nrbnrb
544
544
please don't remove the snippet if you edit my entry
– nrb
Oct 29 '18 at 19:22
add a comment |
please don't remove the snippet if you edit my entry
– nrb
Oct 29 '18 at 19:22
please don't remove the snippet if you edit my entry
– nrb
Oct 29 '18 at 19:22
please don't remove the snippet if you edit my entry
– nrb
Oct 29 '18 at 19:22
add a comment |
1 2
next
protected by VisioN Feb 27 '13 at 8:52
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?
8
I changed JSON to JavaScript (object) to avoid confusing of object literals and JSON.
– Felix Kling
Mar 29 '12 at 16:48
While iterating over collection, you should care about optimization. As it may effect page performance.
– Zaheer Ahmed
Jan 11 '14 at 20:56
Pretty Print Javascript: j11y.io/demos/prettyprint I'm a huge fan of the dump function ajaxian.com/archives/javascript-variable-dump-in-coldfusion
– Kiquenet
Sep 4 '17 at 11:34
dump function: github.com/ozmartian/js-cfdump
– Kiquenet
Sep 4 '17 at 11:48