Javascript 如何在javascript中迭代(键,值)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34913675/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to iterate (keys, values) in javascript?
提问by nbroeking
I have a dictionary that has the format of
我有一本字典,格式为
dictionary = {0: {object}, 1:{object}, 2:{object}}
How can I iterate through this dictionary by doing something like
我怎样才能通过做类似的事情来遍历这本字典
for((key,value) in dictionary){
//Do stuff where key would be 0 and value would be the object
}
回答by thefourtheye
tl;dr
tl;博士
- In ECMAScript 5, it is not possible.
- In ECMAScript 2015, it is possible with
Maps. - In ECMAScript 2017, it would be readily available.
- 在 ECMAScript 5 中,这是不可能的。
- 在 ECMAScript 2015 中,可以使用
Maps。 - 在 ECMAScript 2017 中,它很容易获得。
ECMAScript 5:
ECMAScript 5:
No, its not possible with objects.
不,它不可能与对象。
You should either iterate with for..in, or Object.keys, like this
您应该像这样使用for..in, 或进行迭代Object.keys
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]);
}
}
Note:The ifcondition above is necessary, only if you want to iterate the properties which are dictionaryobject's very own. Because for..inwill iterate through all the inherited enumerable properties.
注意:上述if条件是必要的,仅当您要迭代dictionary对象自己的属性时。因为for..in会遍历所有继承的可枚举属性。
Or
或者
Object.keys(dictionary).forEach(function(key) {
console.log(key, dictionary[key]);
});
ECMAScript 2015
ECMAScript 2015
In ECMAScript 2015, you can use Mapobjects and iterate them with Map.prototype.entries. Quoting example from that page,
在 ECMAScript 2015 中,您可以使用Map对象并使用Map.prototype.entries. 引用该页面的示例,
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 with for..of, like this
或者for..of像这样迭代
'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);
}
Output
输出
[ '0', 'foo' ]
[ 1, 'bar' ]
[ {}, 'baz' ]
Or
或者
for (const [key, value] of myMap.entries()) {
console.log(key, value);
}
Output
输出
0 foo
1 bar
{} baz
ECMAScript 2017
ECMAScript 2017
ECMAScript 2017 would introduce a new function Object.entries. You can use this to iterate the object as you wanted.
ECMAScript 2017 将引入一个新函数Object.entries。您可以根据需要使用它来迭代对象。
'use strict';
const object = {'a': 1, 'b': 2, 'c' : 3};
for (const [key, value] of Object.entries(object)) {
console.log(key, value);
}
Output
输出
a 1
b 2
c 3
回答by alex10
Try this:
尝试这个:
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"}
回答by Loilo
The Object.entries()method has been specified in ES2017 (and is supported in all modern browsers):
该Object.entries()方法已在 ES2017 中指定(并且在所有现代浏览器中均受支持):
for (const [ key, value ] of Object.entries(dictionary)) {
// do something with `key` and `value`
}
Explanation:
解释:
Object.entries()takes an object like{ a: 1, b: 2, c: 3 }and turns it into an array of key-value pairs:[ [ 'a', 1 ], [ 'b', 2 ], [ 'c', 3 ] ].With
for ... ofwe can loop over the entries of the so created array.Since we are guaranteedthat each of the so iterated array items is itself a two-entry array, we can use destructuringto directly assign variables
keyandvalueto its first and second item.
Object.entries()采用类的对象{ a: 1, b: 2, c: 3 },并把它变成键-值对的数组:[ [ 'a', 1 ], [ 'b', 2 ], [ 'c', 3 ] ]。随着
for ... of我们可以遍历所谓创建的数组的条目。由于我们保证,每个迭代使阵列项目本身是一个双项阵列,我们可以用解构直接分配变量
key,并value在其第一和第二项。
回答by Dhaval Chaudhary
You can do something like this :
你可以这样做:
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
}
回答by AMACB
Try this:
尝试这个:
var value;
for (var key in dictionary) {
value = dictionary[key];
// your code here...
}
回答by Steve
WELCOME TO 2020 *Drools in ES6*
欢迎来到 2020 * ES6 中的 Drools*
Theres some pretty old answers in here - take advantage of destructuring. In my opinion this is without a doubt the nicest (very readable) way to iterate an object.
这里有一些非常古老的答案 - 利用解构。在我看来,这无疑是迭代对象的最好(非常易读)的方式。
Object.entries(myObject).forEach(([k,v]) => {
console.log("The key: ",k)
console.log("The value: ",v)
})
回答by Jonathan
I think the fast and easy way is
我认为快速简便的方法是
Object.entries(event).forEach(k => {
console.log("properties ... ", k[0], k[1]); });
just check the documentation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
只需查看文档 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
回答by deeshank
using swagger-ui.js
使用 swagger-ui.js
you can do this -
你可以这样做 -
_.forEach({ 'a': 1, 'b': 2 }, function(n, key) {
console.log(n, key);
});
回答by kloddant
As an improvement to the accepted answer, in order to reduce nesting, you could do this instead:
作为对已接受答案的改进,为了减少嵌套,您可以这样做:
for (var key in dictionary) {
if (!dictionary.hasOwnProperty(key)) {
continue;
}
console.log(key, dictionary[key]);
}
回答by Michael Piper
You can use below script.
您可以使用以下脚本。
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);
}
outputs
1 a
2 b
c 3
输出
1 a
2 b
c 3

