object - How to iterate (keys, values) in javascript? -
i have dictionary has format of
dictionary = {0: {object}, 1:{object}, 2:{object}}
how can iterate through dictionary doing like
for((key,value) in dictionary){ //do stuff key 0 , value object }
no, not possible javascript objects.
you should either iterate for..in
, or object.keys
, this
for (var key in dictionary) { if (dictionary.hasownproperty(key) { console.log(key, dictionary[key]); } }
note: if
condition above necessary, if want iterate properties dictionary
object's own. because for..in
iterate through inherited enumerable properties.
or
object.keys(dictionary).foreach(function(currentkey) { console.log(key, dictionary[key]); });
in ecma script 2015, can use map
objects , iterate them map.prototype.entries
. quoting example page,
var mymap = new map(); mymap.set("0", "foo"); mymap.set(1, "bar"); mymap.set({}, "baz"); var mapiter = mymap.entries(); console.log(mapiter.next().value); // ["0", "foo"] console.log(mapiter.next().value); // [1, "bar"] console.log(mapiter.next().value); // [object, "baz"]
or iterate for..of
, this
'use strict'; var mymap = new map(); mymap.set("0", "foo"); mymap.set(1, "bar"); mymap.set({}, "baz"); (const entry of mymap.entries()) { console.log(entry); }
output
[ '0', 'foo' ] [ 1, 'bar' ] [ {}, 'baz' ]
Comments
Post a Comment