Jak iterować (klucze, wartości) w javascript?

Mam słownik, który ma format

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

Jak mogę przejrzeć ten słownik robiąc coś takiego

for((key,value) in dictionary){
  //Do stuff where key would be 0 and value would be the object
}
Author: thefourtheye, 2016-01-21

7 answers

Tl; dr

  1. W ECMAScript 5 nie jest to możliwe.
  2. W ECMAScript 2015 jest to możliwe dzięki Map s.
  3. W ECMAScript 2017, byłoby łatwo dostępne.

ECMAScript 5:

Nie, to niemożliwe z obiektami.

Powinieneś albo iterować z for..in, lub Object.keys, like this

for (var key in dictionary) {
    // check if the property/key is defined in the object itself, not in parent
    if (dictionary.hasOwnProperty(key)) {           
        console.log(key, dictionary[key]);
    }
}

Uwaga: powyższy warunek if jest konieczny, tylko jeśli chcesz iteracja właściwości, które są obiektami dictionary. Ponieważ for..in będzie iterować przez wszystkie odziedziczone właściwości wyliczeniowe.

Lub

Object.keys(dictionary).forEach(function(key) {
    console.log(key, dictionary[key]);
});

ECMAScript 2015

W ECMAScript 2015 Można używać obiektów Map i iteracji ich za pomocą Map.prototype.entries. Cytując przykład z tej strony,

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

Lub iterować z for..of, jak to

'use strict';

var myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");

for (const entry of myMap.entries()) {
  console.log(entry);
}

Wyjście

[ '0', 'foo' ]
[ 1, 'bar' ]
[ {}, 'baz' ]

Lub

for (const [key, value] of myMap.entries()) {
  console.log(key, value);
}

Wyjście

0 foo
1 bar
{} baz

ECMAScript 2017

ECMAScript 2017 wprowadzi nową funkcję Object.entries. Możesz użyć tego do iteracji obiektu, jak chcesz.

'use strict';

const object = {'a': 1, 'b': 2, 'c' : 3};
for (const [key, value] of Object.entries(object)) {
  console.log(key, value);
}

Wyjście

a 1
b 2
c 3
 182
Author: thefourtheye,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-17 04:03:26

Spróbuj tego:

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"}
 19
Author: alex10,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-14 23:13:01

Od ES2017 metoda Object.entries() wymieniona w pytaniu pierwszy komentarz została znormalizowana:

for (const [ key, value ] of Object.entries(dictionary)) {
    // do something with `key` and `value`
}

Explanation:

 19
Author: Loilo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-30 06:28:54

Spróbuj tego:

var value;
for (var key in dictionary) {
    value = dictionary[key];
    // your code here...
}
 6
Author: AMACB,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-21 01:14:59

Możesz zrobić coś takiego:

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
}
 3
Author: Dhaval Chaudhary,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-17 08:48:06

Myślę, że szybki i łatwy sposób jest

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

Wystarczy sprawdzić dokumentację https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

 1
Author: Jonathan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-26 11:38:00

Używanie swagger-ui.js

Możesz to zrobić -

_.forEach({ 'a': 1, 'b': 2 }, function(n, key) {
    console.log(n, key);
 });
 0
Author: deeshank,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-29 23:42:13