我有一本格式为的字典

dictionary = {0: {object}, 1:{object}, 2:{object}}

我如何通过这样的方式遍历这个字典

for ((key, value) in dictionary) {
    //Do stuff where key would be 0 and value would be the object
}

当前回答

作为对接受答案的改进,为了减少嵌套,你可以这样做,只要键不是继承的:

for (var key in dictionary) {
    if (!dictionary.hasOwnProperty(key)) {
        continue;
    }
    console.log(key, dictionary[key]);
}

编辑:关于对象的信息。hasOwnProperty这里

其他回答

你可以这样做:

dictionary = {'ab': {object}, 'cd':{object}, 'ef':{object}}
var keys = Object.keys(dictionary);

for(var i = 0; i < keys.length;i++){
   //keys[i] for key
   //dictionary[keys[i]] for the value
}

试试这个:

dict = {0:{1:'a'}, 1:{2:'b'}, 2:{3:'c'}}
for (var key in dict){
  console.log( key, dict[key] );
}

0 Object { 1="a"}
1 Object { 2="b"}
2 Object { 3="c"}

你可以使用JavaScript forEach循环:

myMap.forEach((value, key) => {
    console.log('value: ', value);
    console.log('key: ', key);
});

您可以使用下面的脚本。

var obj={1:"a",2:"b",c:"3"};
for (var x=Object.keys(obj),i=0;i<x.length,key=x[i],value=obj[key];i++){
    console.log(key,value);
}

输出 1 2 b c 3

试试这个:

var value;
for (var key in dictionary) {
    value = dictionary[key];
    // your code here...
}