I have an object in JavaScript:
我有一个JavaScript对象:
{
abc: '...',
bca: '...',
zzz: '...',
xxx: '...',
ccc: '...',
// ...
}
I want to use a for
loop 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 for
loop:
用一个简单的数组,我可以用一个标准的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?
但是如何用对象来做呢?
11 个解决方案
#1
433
For most objects, use for .. in
:
对于大多数对象,用于。:
for (var key in yourobject) {
console.log(key, yourobject[key]);
}
To avoid logging inherited properties, check with hasOwnProperty :
要避免记录继承的属性,请检查hasOwnProperty:
for (var key in yourobject) {
if (yourobject.hasOwnProperty(key)) {
console.log(key, yourobject[key]);
}
}
This MDN documentation explains 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
如果您想要“以块的形式”执行,最好的方法是提取数组中的键。由于订单没有保证,这是正确的方式。在现代浏览器中,您可以使用。
var keys = Object.keys(yourobject);
To be more compatible, you'd better do this :
为了更加兼容,你最好这样做:
var keys = [];
for (var key in yourobject) {
if (yourobject.hasOwnProperty(key)) keys.push(key);
}
Then you can iterate on your properties by index: yourobject[keys[i]]
:
然后你可以通过索引:yourobject[key [i]:
for (var i=300; i<keys.length && i<600; i++) {
console.log(keys[i], yourobject[keys[i]]);
}
#2
41
Here is another iteration solution for modern browsers:
下面是现代浏览器的另一个迭代解决方案:
Object.keys(obj).filter(function(k, i) {
return i >= 100 && i < 300;
}).forEach(function(k) {
console.log(obj[k]);
});
Or even shorter:
或更短:
Object.keys(obj).forEach(function(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对象中的属性没有排序,即没有排序。
#3
9
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特性,您不必再使用对象来迭代散列。你可以用地图。Javascript映射保持键的插入顺序,这意味着您可以在不需要检查hasOwnProperty的情况下对它们进行迭代,而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"
#4
7
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+。
#5
5
Using Object.entries
you do something like this.
使用对象。条目你做这样的事情。
// 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 key
and value
for each of the object and get something like this.
所以你可以遍历对象并为每个对象设置键和值,得到这样的东西。
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文档中的对象条目
#6
1
If you wanted to iterate the whole object at once you could use for in
loop:
如果你想一次迭代整个对象,你可以用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:
我能想到的另一个解决方案是使用数组而不是对象:
var obj = [['key1', 'value1'], ['key2', 'value2']];
Then, standard for
loop will work.
然后,标准的循环就可以工作了。
#7
1
->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)
})
#8
1
You can try using lodash- A modern JavaScript utility library delivering modularity, performance & extras js to fast object iterate:-
您可以尝试使用lodash-一个现代JavaScript实用程序库,提供模块化、性能和附加js,以快速对象迭代:-
var users = {
'fred': {
'user': 'fred',
'age': 40
},
'pebbles': {
'user': 'pebbles',
'age': 1
}
};
_.mapValues(users, function(o) {
return o.age;
});
// => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
// The `_.property` iteratee shorthand.
console.log(_.mapValues(users, 'age')); // returns age property & value
console.log(_.mapValues(users, 'user')); // returns user property & value
console.log(_.mapValues(users)); // returns all objects
// => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash-compat/3.10.2/lodash.js"></script>
#9
1
Really a PITA this is not part of standard Javascript.
实际上,这不是标准Javascript的一部分。
/**
* Iterates the keys and values of an object. Object.keys is used to extract the keys.
* @param object The object to iterate
* @param fn (value,key)=>{}
*/
objectForEach(object, fn) {
Object.keys(object).forEach(key => {
fn(object[key],key, object)
})
}
Note: I switched the callback parameters to (value,key) and added a third object to make the API consistent other APIs.
注意:我将回调参数切换到(value,key)并添加了第三个对象,以使API与其他API保持一致。
Use it like this
这样使用
const o = {a:1, b:true};
objectForEach(o, (value, key, obj)=>{
// do something
});
#10
0
var Dictionary = {
If: {
you: {
can: '',
make: ''
},
sense: ''
},
of: {
the: {
sentence: {
it: '',
worked: ''
}
}
}
};
function Iterate(obj) {
for (prop in obj) {
if (obj.hasOwnProperty(prop) && isNaN(prop)) {
console.log(prop + ': ' + obj[prop]);
Iterate(obj[prop]);
}
}
}
Iterate(Dictionary);
#11
0
I finally came up with a handy utility function with a unified interface to iterate Objects, Strings, Arrays, TypedArrays, Maps, Sets, (any Iterables).
我终于想出了一个有用的函数,它有一个统一的接口来迭代对象、字符串、数组、类型射线、映射、集合(任何可迭代的东西)。
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
https://github.com/alrik/iterate-javascript
https://github.com/alrik/iterate-javascript
#1
433
For most objects, use for .. in
:
对于大多数对象,用于。:
for (var key in yourobject) {
console.log(key, yourobject[key]);
}
To avoid logging inherited properties, check with hasOwnProperty :
要避免记录继承的属性,请检查hasOwnProperty:
for (var key in yourobject) {
if (yourobject.hasOwnProperty(key)) {
console.log(key, yourobject[key]);
}
}
This MDN documentation explains 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
如果您想要“以块的形式”执行,最好的方法是提取数组中的键。由于订单没有保证,这是正确的方式。在现代浏览器中,您可以使用。
var keys = Object.keys(yourobject);
To be more compatible, you'd better do this :
为了更加兼容,你最好这样做:
var keys = [];
for (var key in yourobject) {
if (yourobject.hasOwnProperty(key)) keys.push(key);
}
Then you can iterate on your properties by index: yourobject[keys[i]]
:
然后你可以通过索引:yourobject[key [i]:
for (var i=300; i<keys.length && i<600; i++) {
console.log(keys[i], yourobject[keys[i]]);
}
#2
41
Here is another iteration solution for modern browsers:
下面是现代浏览器的另一个迭代解决方案:
Object.keys(obj).filter(function(k, i) {
return i >= 100 && i < 300;
}).forEach(function(k) {
console.log(obj[k]);
});
Or even shorter:
或更短:
Object.keys(obj).forEach(function(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对象中的属性没有排序,即没有排序。
#3
9
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特性,您不必再使用对象来迭代散列。你可以用地图。Javascript映射保持键的插入顺序,这意味着您可以在不需要检查hasOwnProperty的情况下对它们进行迭代,而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"
#4
7
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+。
#5
5
Using Object.entries
you do something like this.
使用对象。条目你做这样的事情。
// 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 key
and value
for each of the object and get something like this.
所以你可以遍历对象并为每个对象设置键和值,得到这样的东西。
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文档中的对象条目
#6
1
If you wanted to iterate the whole object at once you could use for in
loop:
如果你想一次迭代整个对象,你可以用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:
我能想到的另一个解决方案是使用数组而不是对象:
var obj = [['key1', 'value1'], ['key2', 'value2']];
Then, standard for
loop will work.
然后,标准的循环就可以工作了。
#7
1
->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)
})
#8
1
You can try using lodash- A modern JavaScript utility library delivering modularity, performance & extras js to fast object iterate:-
您可以尝试使用lodash-一个现代JavaScript实用程序库,提供模块化、性能和附加js,以快速对象迭代:-
var users = {
'fred': {
'user': 'fred',
'age': 40
},
'pebbles': {
'user': 'pebbles',
'age': 1
}
};
_.mapValues(users, function(o) {
return o.age;
});
// => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
// The `_.property` iteratee shorthand.
console.log(_.mapValues(users, 'age')); // returns age property & value
console.log(_.mapValues(users, 'user')); // returns user property & value
console.log(_.mapValues(users)); // returns all objects
// => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash-compat/3.10.2/lodash.js"></script>
#9
1
Really a PITA this is not part of standard Javascript.
实际上,这不是标准Javascript的一部分。
/**
* Iterates the keys and values of an object. Object.keys is used to extract the keys.
* @param object The object to iterate
* @param fn (value,key)=>{}
*/
objectForEach(object, fn) {
Object.keys(object).forEach(key => {
fn(object[key],key, object)
})
}
Note: I switched the callback parameters to (value,key) and added a third object to make the API consistent other APIs.
注意:我将回调参数切换到(value,key)并添加了第三个对象,以使API与其他API保持一致。
Use it like this
这样使用
const o = {a:1, b:true};
objectForEach(o, (value, key, obj)=>{
// do something
});
#10
0
var Dictionary = {
If: {
you: {
can: '',
make: ''
},
sense: ''
},
of: {
the: {
sentence: {
it: '',
worked: ''
}
}
}
};
function Iterate(obj) {
for (prop in obj) {
if (obj.hasOwnProperty(prop) && isNaN(prop)) {
console.log(prop + ': ' + obj[prop]);
Iterate(obj[prop]);
}
}
}
Iterate(Dictionary);
#11
0
I finally came up with a handy utility function with a unified interface to iterate Objects, Strings, Arrays, TypedArrays, Maps, Sets, (any Iterables).
我终于想出了一个有用的函数,它有一个统一的接口来迭代对象、字符串、数组、类型射线、映射、集合(任何可迭代的东西)。
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
https://github.com/alrik/iterate-javascript
https://github.com/alrik/iterate-javascript