我有一本格式为的字典

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
}

当前回答

我认为最快最简单的方法是

Object.entries(event).forEach(k => {
    console.log("properties ... ", k[0], k[1]); });

看看文档就知道了 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

其他回答

你可以这样做:

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"}

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

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

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

我认为最快最简单的方法是

Object.entries(event).forEach(k => {
    console.log("properties ... ", k[0], k[1]); });

看看文档就知道了 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

试试这个:

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