如何遍历 JavaScript 对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14379274/
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 over a JavaScript object?
提问by nkuhta
I have an object in JavaScript:
我在 JavaScript 中有一个对象:
{
abc: '...',
bca: '...',
zzz: '...',
xxx: '...',
ccc: '...',
// ...
}
I want to use a forloop to get its properties. And I want to iterate it in parts (not all object properties at once).
我想使用for循环来获取其属性。我想分部分迭代它(不是一次所有的对象属性)。
With a simple array I can do it with a standard forloop:
使用一个简单的数组,我可以使用标准for循环来完成:
for (i = 0; i < 100; i++) { ... } // first part
for (i = 100; i < 300; i++) { ... } // second
for (i = 300; i < arr.length; i++) { ... } // last
But how to do it with objects?
但是如何处理对象呢?
回答by Denys Séguret
For most objects, use for .. in:
对于大多数对象,请使用for .. in:
for (let key in yourobject) {
console.log(key, yourobject[key]);
}
With ES6, if you need both keys and values simultaneously, do
使用 ES6,如果您同时需要键和值,请执行
for (let [key, value] of Object.entries(yourobject)) {
console.log(key, value);
}
To avoid logging inherited properties, check with hasOwnProperty:
为避免记录继承的属性,请检查hasOwnProperty:
for (let key in yourobject) {
if (yourobject.hasOwnProperty(key)) {
console.log(key, yourobject[key]);
}
}
You don't need to check hasOwnPropertywhen iterating on keys if you're using a simple object (for example one you made yourself with {}).
hasOwnProperty如果您使用的是一个简单的对象(例如您自己制作的对象),则不需要在对键进行迭代时进行检查{}。
This MDN documentationexplains more generally how to deal with objects and their properties.
这个 MDN 文档更一般地解释了如何处理对象及其属性。
If you want to do it "in chunks", the best is to extract the keys in an array. As the order isn't guaranteed, this is the proper way. In modern browsers, you can use
如果您想“分块”执行此操作,最好的方法是提取数组中的键。由于不能保证顺序,这是正确的方法。在现代浏览器中,您可以使用
let keys = Object.keys(yourobject);
To be more compatible, you'd better do this :
为了更兼容,你最好这样做:
let keys = [];
for (let key in yourobject) {
if (yourobject.hasOwnProperty(key)) keys.push(key);
}
Then you can iterate on your properties by index: yourobject[keys[i]]:
然后你可以通过索引迭代你的属性yourobject[keys[i]]::
for (let i=300; i < keys.length && i < 600; i++) {
console.log(keys[i], yourobject[keys[i]]);
}
回答by VisioN
Here is another iteration solution for modern browsers:
这是现代浏览器的另一个迭代解决方案:
Object.keys(obj)
.filter((k, i) => i >= 100 && i < 300)
.forEach(k => console.log(obj[k]));
Or without the filter function:
或者没有过滤功能:
Object.keys(obj).forEach((k, i) => {
if (i >= 100 && i < 300) {
console.log(obj[k]);
}
});
However you must consider that properties in JavaScript object are not sorted, i.e. have no order.
但是,您必须考虑到 JavaScript 对象中的属性没有排序,即没有顺序。
回答by Adeel Imran
Using Object.entriesyou do something like this.
使用Object.entries你做这样的事情。
// array like object with random key ordering
const anObj = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.entries(anObj)); // [ ['2', 'b'],['7', 'c'],['100', 'a'] ]
The Object.entries() method returns an array of a given object's own enumerable property [key, value]
Object.entries() 方法返回给定对象自己的可枚举属性 [key, value] 的数组
So you can iterate over the Object and have keyand valuefor each of the object and get something like this.
所以,你可以遍历对象,并有key与value每个对象,并得到这样的事情。
const anObj = { 100: 'a', 2: 'b', 7: 'c' };
Object.entries(anObj).map(obj => {
const key = obj[0];
const value = obj[1];
// do whatever you want with those values.
});
or like this
或者像这样
// Or, using array extras
Object.entries(obj).forEach(([key, value]) => {
console.log(`${key} ${value}`); // "a 5", "b 7", "c 9"
});
For a reference have a look at the MDN docs for Object Entries
有关参考,请查看对象条目的 MDN 文档
回答by Paul
With the new ES6/ES2015 features, you don't have to use an object anymore to iterate over a hash. You can use a Map. Javascript Maps keep keys in insertion order, meaning you can iterate over them without having to check the hasOwnProperty, which was always really a hack.
使用新的 ES6/ES2015 功能,您不必再使用对象来迭代哈希。您可以使用Map。Javascript Maps 以插入顺序保存键,这意味着您可以迭代它们而无需检查 hasOwnProperty,这一直是一个真正的黑客。
Iterate over a map:
迭代地图:
var myMap = new Map();
myMap.set(0, "zero");
myMap.set(1, "one");
for (var [key, value] of myMap) {
console.log(key + " = " + value);
}
// Will show 2 logs; first with "0 = zero" and second with "1 = one"
for (var key of myMap.keys()) {
console.log(key);
}
// Will show 2 logs; first with "0" and second with "1"
for (var value of myMap.values()) {
console.log(value);
}
// Will show 2 logs; first with "zero" and second with "one"
for (var [key, value] of myMap.entries()) {
console.log(key + " = " + value);
}
// Will show 2 logs; first with "0 = zero" and second with "1 = one"
or use forEach:
或使用 forEach:
myMap.forEach(function(value, key) {
console.log(key + " = " + value);
}, myMap)
// Will show 2 logs; first with "0 = zero" and second with "1 = one"
回答by Derek Soike
If you want the key and valuewhen iterating, you can use a for...ofloop with Object.entries.
如果您在迭代时需要键和值,您可以对Object.entries使用for...of循环。
const myObj = {a: 1, b: 2}
for (let [key, value] of Object.entries(myObj)) {
console.log(`key=${key} value=${value}`)
}
// output:
// key=a value=1
// key=b value=2
回答by Cerbrus
The only reliable way to do this would be to save your object data to 2 arrays, one of keys, and one for the data:
唯一可靠的方法是将对象数据保存到 2 个数组中,一个是键,另一个是用于数据:
var keys = [];
var data = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
keys.push(key);
data.push(obj[key]); // Not necessary, but cleaner, in my opinion. See the example below.
}
}
You can then iterate over the arrays like you normally would:
然后,您可以像往常一样遍历数组:
for(var i = 0; i < 100; i++){
console.log(keys[i], data[i]);
//or
console.log(keys[i], obj[keys[i]]); // harder to read, I think.
}
for(var i = 100; i < 300; i++){
console.log(keys[i], data[i]);
}
I am not using Object.keys(obj), because that's IE 9+.
我没有使用Object.keys(obj),因为那是 IE 9+。
回答by ashishdudhat
->if we iterate over a JavaScript object using and find key of array of objects
->如果我们使用并找到对象数组的键来遍历 JavaScript 对象
Object.keys(Array).forEach(key => {
console.log('key',key)
})
回答by Willem van der Veen
For object iteration we usually use a for..inloop. This structure will loop through all enumerableproperties, including ones who are inherited via prototypal inheritance. For example:
对于对象迭代,我们通常使用for..in循环。该结构将遍历所有可枚举属性,包括通过原型继承继承的属性。例如:
let obj = {
prop1: '1',
prop2: '2'
}
for(let el in obj) {
console.log(el);
console.log(obj[el]);
}
However, for..inwill loop over all enumerable elements and this will not able us to split the iteration in chunks. To achieve this we can use the built in Object.keys()function to retrieve all the keys of an object in an array. We then can split up the iteration into multiple for loops and access the properties using the keys array. For example:
但是,for..in将循环遍历所有可枚举元素,这将无法将迭代拆分为块。为了实现这一点,我们可以使用内置Object.keys()函数来检索数组中对象的所有键。然后,我们可以将迭代拆分为多个 for 循环并使用 keys 数组访问属性。例如:
let obj = {
prop1: '1',
prop2: '2',
prop3: '3',
prop4: '4',
};
const keys = Object.keys(obj);
console.log(keys);
for (let i = 0; i < 2; i++) {
console.log(obj[keys[i]]);
}
for (let i = 2; i < 4; i++) {
console.log(obj[keys[i]]);
}
回答by Micha? Miszczyszyn
If you wanted to iterate the whole object at once you could use for inloop:
如果你想一次迭代整个对象,你可以使用for in循环:
for (var i in obj) {
...
}
But if you want to divide the object into parts in fact you cannot. There's no guarantee that properties in the object are in any specified order. Therefore, I can think of two solutions.
但如果你想把对象分成几部分,实际上你不能。不能保证对象中的属性按任何指定的顺序排列。因此,我可以想到两种解决方案。
First of them is to "remove" already read properties:
首先是“删除”已经读取的属性:
var i = 0;
for (var key in obj) {
console.log(obj[key]);
delete obj[key];
if ( ++i > 300) break;
}
Another solution I can think of is to use Array of Arrays instead of the object:
我能想到的另一个解决方案是使用 Array of Arrays 而不是对象:
var obj = [['key1', 'value1'], ['key2', 'value2']];
Then, standard forloop will work.
然后,标准for循环将起作用。
回答by Alrik Zachert
I finally came up with a handy utility function with a unified interface to iterate Objects, Strings, Arrays, TypedArrays, Maps, Sets, (any Iterables).
我终于想出了一个方便的实用程序函数,它有一个统一的接口来迭代对象、字符串、数组、TypedArrays、地图、集合(任何可迭代对象)。
const iterate = require('@a-z/iterate-it');
const obj = { a: 1, b: 2, c: 3 };
iterate(obj, (value, key) => console.log(key, value));
// a 1
// b 2
// c 3

