[英]How to iterate (keys, values) in JavaScript?
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
}
Object.entries(yourObj)
.Object.entries(yourObj)
。Map
s.Map
。 ECMAScript 2017 introduced a new Object.entries
function. ECMAScript 2017 引入了一个新的
Object.entries
函数。 You can use this to iterate the object as you wanted.您可以根据需要使用它来迭代对象。
'use strict';
const object = {'a': 1, 'b': 2, 'c' : 3};
for (const [key, value] of Object.entries(object)) {
console.log(key, value);
}
a 1
b 2
c 3
In ECMAScript 2015, there is not Object.entries
but you can use Map
objects instead and iterate over them with Map.prototype.entries
.在 ECMAScript 2015 中,没有
Object.entries
但您可以使用Map
对象代替并使用Map.prototype.entries
迭代它们。 Quoting the example from that 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 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);
}
[ '0', 'foo' ]
[ 1, 'bar' ]
[ {}, 'baz' ]
Or或者
for (const [key, value] of myMap.entries()) {
console.log(key, value);
}
0 foo
1 bar
{} baz
No, it's 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 if
condition above is necessary only if you want to iterate over the properties which are the dictionary
object's very own.注意:只有当您想遍历
dictionary
对象自己的属性时,才需要上面的if
条件。 Because for..in
will iterate through all the inherited enumerable properties.因为
for..in
将遍历所有继承的可枚举属性。
Or或者
Object.keys(dictionary).forEach(function(key) {
console.log(key, dictionary[key]);
});
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"}
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 ] ]
. Object.entries()
接受像{ a: 1, b: 2, c: 3 }
并将其转换为键值对数组: [ [ 'a', 1 ], [ 'b', 2 ], [ 'c', 3 ] ]
。
With for ... of
we can loop over the entries of the so created array.使用
for ... of
我们可以遍历如此创建的数组的条目。
Since we are guaranteed that each of the so iterated array items is itself a two-entry array, we can use destructuring to directly assign variables key
and value
to its first and second item.由于我们保证每个如此迭代的数组项本身都是一个双条目数组,因此我们可以使用解构将变量
key
和value
直接分配给它的第一项和第二项。
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.
在我看来,这无疑是迭代对象的最好(非常易读)的方式。
const myObject = { nick: 'cage', phil: 'murray', }; Object.entries(myObject).forEach(([k,v]) => { console.log("The key: ", k) console.log("The value: ", v) })
Edit:编辑:
As mentioned by Lazerbeak, map
allows you to cycle an object and use the key and value to make an array.正如 Lazerbeak 所提到的,
map
允许您循环一个对象并使用键和值来制作数组。
const myObject = { nick: 'cage', phil: 'murray', }; const myArray = Object.entries(myObject).map(([k, v]) => { return `The key '${k}' has a value of '${v}'`; }); console.log(myArray);
Edit 2:编辑2:
To explain what is happening in the line of code:解释代码行中发生的事情:
Object.entries(myObject).forEach(([k,v]) => {}
Object.entries()
converts our object to an array of arrays: Object.entries()
将我们的对象转换为数组数组:
[["nick", "cage"], ["phil", "murray"]]
Then we use forEach on the outer array:然后我们在外部数组上使用 forEach:
1st loop: ["nick", "cage"]
2nd loop: ["phil", "murray"]
Then we "destructure" the value (which we know will always be an array) with ([k,v])
so k
becomes the first name and v
becomes the last name.然后我们用
([k,v])
“解构”这个值(我们知道它永远是一个数组),所以k
成为名字, v
成为姓氏。
Try this:尝试这个:
var value;
for (var key in dictionary) {
value = dictionary[key];
// your code here...
}
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
}
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
using swagger-ui.js使用 swagger-ui.js
you can do this -你可以这样做 -
_.forEach({ 'a': 1, 'b': 2 }, function(n, key) {
console.log(n, key);
});
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 1个
2 b 2 乙
c 3 3
As an improvement to the accepted answer, in order to reduce nesting, you could do this instead, provided that the key is not inherited:作为对已接受答案的改进,为了减少嵌套,您可以改为这样做,前提是密钥不是继承的:
for (var key in dictionary) {
if (!dictionary.hasOwnProperty(key)) {
continue;
}
console.log(key, dictionary[key]);
}
Edit: info about Object.hasOwnProperty
here编辑:关于
Object.hasOwnProperty
信息在这里
You can use JavaScript forEach
Loop:您可以使用 JavaScript
forEach
循环:
myMap.forEach((value, key) => {
console.log('value: ', value);
console.log('key: ', key);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.