如何循环或枚举一个JavaScript对象?

时间:2022-10-30 10:23:46

I have a JavaScript object like the following:

我有一个JavaScript对象,如下所示:

var p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3"
};

Now I want to loop through all p elements (p1,p2,p3...) and get their keys and values. How can I do that?

现在我要循环遍历所有p元素(p1,p2,p3…)并得到它们的键和值。我怎么做呢?

I can modify the JavaScript object if necessary. My ultimate goal is to loop through some key value pairs and if possible I want to avoid using eval.

如果需要,我可以修改JavaScript对象。我的最终目标是遍历一些键值对,如果可能的话,我希望避免使用eval。

29 个解决方案

#1


3408  

You can use the for-in loop as shown by others. However, you also have to make sure that the key you get is an actual property of an object, and doesn't come from the prototype.

您可以像其他人一样使用forin循环。但是,您还必须确保获得的键是对象的实际属性,而不是来自原型。

Here is the snippet:

这是代码片段:

var p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3"
};

for (var key in p) {
    if (p.hasOwnProperty(key)) {
        console.log(key + " -> " + p[key]);
    }
}

#2


599  

Under ECMAScript 5, you can combine Object.keys() and Array.prototype.forEach():

在ECMAScript 5下,您可以将Object.keys()和Array.prototype.forEach()组合在一起:

var obj = { first: "John", last: "Doe" };

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

ES6 adds for...of:

对…的ES6补充说:

for (const key of Object.keys(obj)) {
    console.log(key, obj[key]);
}

ES2017 adds Object.entries() which avoids having to look up each value in the original object:

ES2017增加object .entries(),避免了查询原始对象中的每个值:

Object.entries(obj).forEach(
    ([key, value]) => console.log(key, value)
);

Both Object.keys() and Object.entries() iterate properties in the same order as a for...in loop but ignore the prototype chain. Only the object's own enumerable properties are iterated.

Object.keys()和Object.entries()都以与for相同的顺序迭代属性。在循环中,但忽略原型链。只迭代对象自己的可枚举属性。

Edit: ES2016 → ES6

编辑:ES2016→ES6

#3


298  

You have to use the for-in loop

你必须使用forin循环

But be very careful when using this kind of loop, because this will loop all the properties along the prototype chain.

但是在使用这种循环时要非常小心,因为这会沿着原型链循环所有的属性。

Therefore, when using for-in loops, always make use of the hasOwnProperty method to determine if the current property in iteration is really a property of the object you're checking on:

因此,在使用forin循环时,一定要使用hasOwnProperty方法来确定迭代中的当前属性是否真的是要检查的对象的属性:

for (var prop in p) {
    if (!p.hasOwnProperty(prop)) {
        //The current property is not a direct property of p
        continue;
    }
    //Do your logic with the property here
}

#4


230  

The question won't be complete if we don't mention about alternative methods for looping through objects.

如果我们不提及循环遍历对象的替代方法,那么这个问题就不会完整。

Nowadays many well known JavaScript libraries provide their own methods for iterating over collections, i.e. over arrays, objects, and array-like objects. These methods are convenient to use and are entirely compatible with any browser.

现在许多著名的JavaScript库都提供了自己的方法来遍历集合,比如遍历数组、对象和类数组的对象。这些方法使用起来很方便,并且与任何浏览器都完全兼容。

  1. If you work with jQuery, you may use jQuery.each() method. It can be used to seamlessly iterate over both objects and arrays:

    如果使用jQuery,可以使用jQuery.each()方法。它可以用来无缝地遍历对象和数组:

    $.each(obj, function(key, value) {
        console.log(key, value);
    });
    
  2. In Underscore.js you can find method _.each(), which iterates over a list of elements, yielding each in turn to a supplied function (pay attention to the order of arguments in iteratee function!):

    在强调。您可以找到method _.each(),它遍历一个元素列表,依次将每个元素转换为一个提供的函数(请注意iteratee函数中的参数顺序!)

    _.each(obj, function(value, key) {
        console.log(key, value);
    });
    
  3. Lo-Dash provides several methods for iterating over object properties. Basic _.forEach() (or it's alias _.each()) is useful for looping through both objects and arrays, however (!) objects with length property are treated like arrays, and to avoid this behavior it is suggested to use _.forIn() and _.forOwn() methods (these also have value argument coming first):

    Lo-Dash提供了几种迭代对象属性的方法。基本的_.forEach()(或者它的别名_.each()))对于遍历对象和数组都是有用的,但是(!)具有长度属性的对象被视为数组,为了避免这种行为,建议使用_.forIn()和_.forOwn()方法(这些方法也首先有值参数):

    _.forIn(obj, function(value, key) {
        console.log(key, value);
    });
    

    _.forIn() iterates over own and inherited enumerable properties of an object, while _.forOwn() iterates only over own properties of an object (basically checking against hasOwnProperty function). For simple objects and object literals any of these methods will work fine.

    _.forIn()迭代一个对象的自己和继承的可枚举属性,而_.forOwn()只迭代一个对象的自己的属性(基本上是检查hasOwnProperty函数)。对于简单的对象和对象文本,任何这些方法都可以正常工作。

Generally all described methods have the same behaviour with any supplied objects. Besides using native for..in loop will usually be faster than any abstraction, such as jQuery.each(), these methods are considerably easier to use, require less coding and provide better error handling.

通常,所有描述的方法与任何提供的对象具有相同的行为。除了使用本机的. .在loop中,通常比任何抽象(如jQuery.each()))都要快,这些方法非常容易使用,需要更少的编码,并提供更好的错误处理。

#5


46  

In ECMAScript 5 you have new approach in iteration fields of literal - Object.keys

在ECMAScript 5中,您在文本- Object.keys的迭代字段中有了新的方法

More information you can see on MDN

您可以在MDN上看到更多的信息。

My choice is below as a faster solution in current versions of browsers (Chrome30, IE10, FF25)

我的选择如下,作为当前版本浏览器中更快的解决方案(Chrome30, IE10, FF25)

var keys = Object.keys(p),
    len = keys.length,
    i = 0,
    prop,
    value;
while (i < len) {
    prop = keys[i];
    value = p[prop];
    i += 1;
}

You can compare performance of this approach with different implementations on jsperf.com:

您可以将这种方法的性能与jsperf.com上的不同实现进行比较:

Browser support you can see on Kangax's compat table

您可以在Kangax的compat表上看到对浏览器的支持

For old browser you have simple and full polyfill

对于旧的浏览器,你有简单和完整的polyfill

UPD:

乌利希期刊指南:

performance comparison for all most popular cases in this question on perfjs.info:

在这个问题上的性能比较:

object literal iteration

对象字面量迭代

#6


29  

You can just iterate over it like:

你可以这样迭代它:

for (var key in p) {
  alert(p[key]);
}

Note that key will not take on the value of the property, it's just an index value.

注意这个键不会取属性的值,它只是一个索引值。

#7


23  

Since es2015 is getting more and more popular I am posting this answer which include usage of generator and iterator to smoothly iterate through [key, value] pairs. As it is possible in other languages for instance Ruby.

由于es2015越来越受欢迎,所以我发布了这个答案,包括使用生成器和迭代器来平滑地迭代[key, value]对。就像在其他语言中一样,例如Ruby。

Ok here is a code:

这里有一个代码:

const MyObject = {
  'a': 'Hello',
  'b': 'it\'s',
  'c': 'me',
  'd': 'you',
  'e': 'looking',
  'f': 'for',
  [Symbol.iterator]: function* () {
    for (const i of Object.keys(this)) {
      yield [i, this[i]];
    }
  }
};

for (const [k, v] of MyObject) {
  console.log(`Here is key ${k} and here is value ${v}`);
}

All information about how can you do an iterator and generator you can find at developer Mozilla page.

关于如何进行迭代器和生成器的所有信息都可以在developer Mozilla页面找到。

Hope It helped someone.

希望它帮助某人。

EDIT:

编辑:

ES2017 will include Object.entries which will make iterating over [key, value] pairs in objects even more easier. It is now known that it will be a part of a standard according to the ts39 stage information.

ES2017将包括对象。在对象中迭代[键,值]对的条目更加容易。根据ts39阶段信息,它将成为标准的一部分。

I think it is time to update my answer to let it became even more fresher than it's now.

我认为是时候更新我的答案了,让它变得比现在更新鲜。

const MyObject = {
  'a': 'Hello',
  'b': 'it\'s',
  'c': 'me',
  'd': 'you',
  'e': 'looking',
  'f': 'for',
};

for (const [k, v] of Object.entries(MyObject)) {
  console.log(`Here is key ${k} and here is value ${v}`);
}

You can find more about usage on MDN page

您可以在MDN页面上找到更多关于用法的信息

#8


17  

via prototype with forEach() which should skip the prototype chain properties:

通过与forEach()的原型,可以跳过原型链属性:

Object.prototype.each = function(f) {
    var obj = this
    Object.keys(obj).forEach( function(key) { 
        f( key , obj[key] ) 
    });
}


//print all keys and values
var obj = {a:1,b:2,c:3}
obj.each(function(key,value) { console.log(key + " " + value) });
// a 1
// b 2
// c 3

#9


14  

After looking through all the answers in here, hasOwnProperty isn't required for my own usage because my json object is clean; there's really no sense in adding any additional javascript processing. This is all I'm using:

在查看了这里的所有答案之后,我自己的使用不需要hasOwnProperty,因为我的json对象是干净的;添加任何额外的javascript处理是没有意义的。这就是我所使用的:

for (var key in p) {
    console.log(key + ' => ' + p[key]);
    // key is key
    // value is p[key]
}

#10


13  

for(key in p) {
  alert( p[key] );
}

Note: you can do this over arrays, but you'll iterate over the length and other properties, too.

注意:可以对数组执行此操作,但也会对长度和其他属性进行迭代。

#11


12  

Object.keys(obj) : Array

种(obj):数组

retrieves all string-valued keys of all enumerable own (non-inherited) properties.

检索所有可枚举自身(非继承)属性的所有字符串值键。

So it gives the same list of keys as you intend by testing each object key with hasOwnProperty. You don't need that extra test operation than and Object.keys( obj ).forEach(function( key ){}) is supposed to be faster. Let's prove it:

因此,它通过使用hasOwnProperty测试每个对象键,给出与您希望的相同的键列表。您不需要额外的测试操作than和Object。键(obj)。对于每一个(函数(键){})都应该更快。让我们证明了这一点:

var uniqid = function(){
			var text = "",
					i = 0,
					possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
			for( ; i < 32; i++ ) {
					text += possible.charAt( Math.floor( Math.random() * possible.length ) );
			}
			return text;
		}, 
		CYCLES = 100000,
		obj = {}, 
		p1,
		p2,
		p3,
		key;

// Populate object with random properties
Array.apply( null, Array( CYCLES ) ).forEach(function(){
	obj[ uniqid() ] = new Date()
});

// Approach #1
p1 = performance.now();
Object.keys( obj ).forEach(function( key ){
	var waste = obj[ key ];
});

p2 = performance.now();
console.log( "Object.keys approach took " + (p2 - p1) + " milliseconds.");

// Approach #2
for( key in obj ) {
	if ( obj.hasOwnProperty( key ) ) {
		var waste = obj[ key ];
	}
}

p3 = performance.now();
console.log( "for...in/hasOwnProperty approach took " + (p3 - p2) + " milliseconds.");

In my Firefox I have following results

在我的Firefox中,我有如下的结果。

  • Object.keys approach took 40.21101451665163 milliseconds.
  • 对象。key方法花费了40.21101451665163毫秒。
  • for...in/hasOwnProperty approach took 98.26163508463651 milliseconds.
  • 为…in/hasOwnProperty方法耗时98.263508463651毫秒。

PS. on Chrome the difference even bigger http://codepen.io/dsheiko/pen/JdrqXa

Chrome上的差异更大http://codepen.io/dsheiko/pen/JdrqXa

PS2: In ES6 (EcmaScript 2015) you can iterate iterable object nicer:

PS2:在ES6 (EcmaScript 2015)中,您可以更好地迭代可迭代对象:

let map = new Map().set('a', 1).set('b', 2);
for (let pair of map) {
    console.log(pair);
}

// OR 
let map = new Map([
    [false, 'no'],
    [true,  'yes'],
]);
map.forEach((value, key) => {
    console.log(key, value);
});

#12


11  

It's interesting people in these answers have touched on both Object.keys() and for...of but never combined them:

有趣的是,在这些答案中,人们同时涉及了Object.keys()和for…但从未将它们结合在一起:

var map = {well:'hello', there:'!'};
for (let key of Object.keys(map))
    console.log(key + ':' + map[key]);

You can't just for...of an Object because it's not an iterator, and for...index or .forEach()ing the Object.keys() is ugly/inefficient.
I'm glad most people are refraining from for...in (with or without checking .hasOwnProperty()) as that's also a bit messy, so other than my answer above, I'm here to say...

你不能只是为了…一个对象,因为它不是迭代器,而且。对Object.keys()进行索引或. foreach()是丑陋的/低效的。我很高兴大多数人不喜欢……in (with or without check .hasOwnProperty()))因为它也有点混乱,所以除了我上面的答案之外,我要说的是……


You can make ordinary object associations iterate! Behaving just like Maps with direct use of the fancy for...of
DEMO working in Chrome and FF (I assume ES6 only)

您可以使普通对象关联迭代!表现得就像地图一样,直接运用想象力……在Chrome和FF中工作的演示(我假设只有ES6)

var ordinaryObject = {well:'hello', there:'!'};
for (let pair of ordinaryObject)
    //key:value
    console.log(pair[0] + ':' + pair[1]);

//or
for (let [key, value] of ordinaryObject)
    console.log(key + ':' + value);

So long as you include my shim below:

只要你在下面写上我的名字:

//makes all objects iterable just like Maps!!! YAY
//iterates over Object.keys() (which already ignores prototype chain for us)
Object.prototype[Symbol.iterator] = function() {
    var keys = Object.keys(this)[Symbol.iterator]();
    var obj = this;
    var output;
    return {next:function() {
        if (!(output = keys.next()).done)
            output.value = [output.value, obj[output.value]];
        return output;
    }};
};

Without having to create a real Map object that doesn't have the nice syntactic sugar.

不需要创建一个真正的映射对象它没有很好的语法糖。

var trueMap = new Map([['well', 'hello'], ['there', '!']]);
for (let pair of trueMap)
    console.log(pair[0] + ':' + pair[1]);

In fact, with this shim, if you still wanted to take advantage of Map's other functionality (without shimming them all in) but still wanted to use the neat object notation, since objects are now iterable you can now just make a Map from it!

实际上,有了这个shim,如果您还想利用Map的其他功能(不需要将它们全部填满),但是仍然想使用整洁的对象表示法,因为对象现在是可迭代的,现在您可以从它创建一个映射!

//shown in demo
var realMap = new Map({well:'hello', there:'!'});

For those who don't like to shim, or mess with prototype in general, feel free to make the function on window instead, calling it something like getObjIterator() then;

对于那些不喜欢shim的人,或者一般的原型,可以*地在窗口中创建函数,然后调用getObjIterator();

//no prototype manipulation
function getObjIterator(obj) {
    //create a dummy object instead of adding functionality to all objects
    var iterator = new Object();

    //give it what the shim does but as its own local property
    iterator[Symbol.iterator] = function() {
        var keys = Object.keys(obj)[Symbol.iterator]();
        var output;

        return {next:function() {
            if (!(output = keys.next()).done)
                output.value = [output.value, obj[output.value]];
            return output;
        }};
    };

    return iterator;
}

Now you can just call it as an ordinary function, nothing else is affected

现在你可以把它称为一个普通的函数,其他的都不受影响。

var realMap = new Map(getObjIterator({well:'hello', there:'!'}))

or

for (let pair of getObjIterator(ordinaryObject))

There's no reason why that wouldn't work.

没有理由说这行不通。

Welcome to the future.

欢迎来到未来。

#13


7  

You can add a simple forEach function to all objects, so you can automatically loop through any object:

您可以为所有对象添加一个简单的forEach函数,因此您可以自动循环遍历任何对象:

Object.defineProperty(Object.prototype, 'forEach', {
    value: function (func) {
        for (var key in this) {
            if (!this.hasOwnProperty(key)) {
                // skip loop if the property is from prototype
                continue;
            }
            var value = this[key];
            func(key, value);
        }
    },
    enumerable: false
});

For those people who don't like the "for ... in"-method:

对于那些不喜欢“For…”的人在“方法:

Object.defineProperty(Object.prototype, 'forEach', {
    value: function (func) {
        var arr = Object.keys(this);
        for (var i = 0; i < arr.length; i++) {
            var key = arr[i];
            func(key, this[key]);
        }
    },
    enumerable: false
});

Now, you can simple call:

现在,你可以简单地调用:

p.forEach (function(key, value){
    console.log ("Key: " + key);
    console.log ("Value: " + value);
});

If you don't want to get conflicts with other forEach-Methods you can name it with your unique name.

如果您不想与其他foreacher方法发生冲突,您可以使用您的惟一名称来命名它。

#14


7  

The Object.keys() method returns an array of a given object's own enumerable properties. Read more about it here

方法的作用是:返回给定对象自己的可枚举属性的数组。在这里阅读更多

var p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3"
};

Object.keys(p).map((key)=> console.log(key + "->" + p[key]))

#15


7  

Here is another method to iterate through an object.

这是另一个遍历对象的方法。

   var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};


Object.keys(p).forEach(key => { console.log(key, p[key]) })

#16


7  

var p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3"
};

for (var key in p) {
    if (p.hasOwnProperty(key)) {
        console.log(key + " = " + p[key]);
    }
}
<p>
  Output:<br>
  p1 = values1<br>
  p2 = values2<br>
  p3 = values3
</p>

#17


5  

Only JavaScript code without dependencies:

只有没有依赖项的JavaScript代码:

var p = {"p1": "value1", "p2": "value2", "p3": "value3"};
keys = Object.keys(p);   // ["p1", "p2", "p3"]

for(i = 0; i < keys.length; i++){
  console.log(keys[i] + "=" + p[keys[i]]);   // p1=value1, p2=value2, p3=value3
}

#18


5  

Loops can be pretty interesting when using pure JavaScript. It seems that only ECMA6 (New 2015 JavaScript specification) got the loops under control. Unfortunately as I'm writing this, both Browsers and popular Integrated development environment (IDE) are still struggling to support completely the new bells and whistles.

当使用纯JavaScript时,循环会非常有趣。似乎只有ECMA6(新的2015 JavaScript规范)控制了循环。不幸的是,当我写这篇文章的时候,浏览器和流行的集成开发环境(IDE)仍然很难完全支持新的功能。

At a glance here is what a JavaScript object loop look like before ECMA6:

这是JavaScript对象循环在ECMA6之前的样子:

for (var key in object) {
  if (p.hasOwnProperty(key)) {
    var value = object[key];
    console.log(key); // This is the key;
    console.log(value); // This is the value;
  }
}

Also, I know this is out of scope with this question but in 2011, ECMAScript 5.1 added the forEach method for Arrays only which basically created a new improved way to loop through arrays while still leaving non iterable objects with the old verbose and confusing for loop. But the odd part is that this new forEach method does not support break which led to all sorts of other problems.

而且,我知道这个问题超出了范围,但是在2011年,ECMAScript 5.1只为数组添加了forEach方法,它基本上创建了一种新的改进方法来循环数组,同时仍然保留不可迭代的对象,使之具有原来的冗长和混乱的for循环。但奇怪的是,这种新的forEach方法不支持中断,这导致了其他各种问题。

Basically in 2011, there is not a real solid way to loop in JavaScript other than what many popular libraries (jQuery, Underscore, etc.) decided to re-implement.

基本上,在2011年,除了许多流行的库(jQuery、下线等)决定重新实现之外,没有一种真正可靠的方法来循环使用JavaScript。

As of 2015, we now have a better out of the box way to loop (and break) any object type (including Arrays and Strings). Here is what a loop in JavaScript will eventually look like when the recommendation becomes mainstream:

到2015年,我们现在有了更好的方法来循环(和中断)任何对象类型(包括数组和字符串)。下面是JavaScript的一个循环,当建议成为主流时,它最终会变成:

for (let [key, value] of Object.entries(object)) {
    console.log(key); // This is the key;
    console.log(value); // This is the value;
}

Note that most browsers won't support the code above as of June 18th 2016. Even in Chrome you need to enable this special flag for it to work: chrome://flags/#enable-javascript-harmony

请注意,到2016年6月18日,大多数浏览器都不支持上述代码。即使是在Chrome中,也需要启用这个特殊的标志:Chrome:/ flags/#启用javascript-harmony

Until this becomes the new standard, the old method can still be used but there are also alternatives in popular libraries or even lightweight alternatives for those who aren't using any of these libraries.

在这成为新的标准之前,旧的方法仍然可以使用,但是在流行的库中还有其他的替代方法,甚至是那些没有使用这些库的人的轻量级替代方案。

#19


4  

I would do this rather than checking obj.hasOwnerProperty within every for ... in loop.

我会这样做,而不是检查obj。每个人拥有的财产……在循环。

var obj = {a : 1};
for(var key in obj){
    //obj.hasOwnProperty(key) is not needed.
    console.log(key);
}
//then check if anybody has messed the native object. Put this code at the end of the page.
for(var key in Object){
    throw new Error("Please don't extend the native object");
}

#20


3  

If you want to iterate over non-enumerable properties as well, you can use Object.getOwnPropertyNames(obj) to return an array of all properties (enumerable or not) found directly upon a given object.

如果您也想遍历非可枚举属性,那么可以使用object. getownpropertynames (obj)来返回直接在给定对象上找到的所有属性(可枚举或非枚举)的数组。

var obj = Object.create({}, {
  // non-enumerable property
  getFoo: {
    value: function() { return this.foo; },
    enumerable: false
  }
});

obj.foo = 1; // enumerable property

Object.getOwnPropertyNames(obj).forEach(function (name) {
  document.write(name + ': ' + obj[name] + '<br/>');
});

#21


3  

Considering ES6 I'd like to add my own spoon of sugar and provide one more approach to iterate over object's properties.

考虑到ES6,我想添加我自己的一勺糖,并提供一种方法来迭代对象的属性。

Since plain JS object isn't iterable just out of box, we aren't able to use for..of loop for iterating over its content. But no one can stop us to make it iterable.

因为普通的JS对象并不是开箱即用的,所以我们不能用for..。循环遍历它的内容。但是没有人能阻止我们使它可迭代。

Let's we have book object.

我们有book object。

let book = {
  title: "Amazing book",
  author: "Me",
  pages: 3
}

book[Symbol.iterator] = function(){

  let properties = Object.keys(this); // returns an array with property names
  let counter = 0;
  let isDone = false;

  let next = () => {
    if(counter >= properties.length){
      isDone = true;
    }
    return { done: isDone, value: this[properties[counter++]] }
  }

  return { next };
}

Since we've made it we can use it this way:

既然我们已经成功了,我们可以这样使用它:

for(let pValue of book){
  console.log(pValue);
}
------------------------
Amazing book
Me
3

Or if you know the power of ES6 generators, so you certainly can make the code above much shorter.

或者如果您知道ES6生成器的功能,那么您当然可以使上面的代码更短。

book[Symbol.iterator] = function *(){

  let properties = Object.keys(this);
  for (let p of properties){
    yield this[p];
  }

}

Sure, you can apply such behavior for all objects with making Object iterable on prototype level.

当然,您可以对所有对象应用这种行为,使对象在原型级上可迭代。

Object.prototype[Symbol.iterator] = function() {...}

Also, objects that comply with the iterable protocol can be used with the new ES2015 feature spread operator thus we can read object property values as an array.

同样,符合iterable协议的对象可以与新的ES2015特性扩展操作符一起使用,这样我们就可以将对象属性值读取为一个数组。

let pValues = [...book];
console.log(pValues);
-------------------------
["Amazing book", "Me", 3]

Or you can use destructuring assignment:

或者你可以使用析构赋值:

let [title, , pages] = book; // notice that we can just skip unnecessary values
console.log(title);
console.log(pages);
------------------
Amazing book
3

You can check out JSFiddle with all code I've provided above.

您可以检查JSFiddle是否包含我上面提供的所有代码。

#22


2  

If anybody needs to loop through arrayObjects with condition:

如果有人需要对arrayObjects进行循环

var arrayObjects = [{"building":"A", "status":"good"},{"building":"B","status":"horrible"}];

for (var i=0; i< arrayObjects.length; i++) {
  console.log(arrayObjects[i]);
  
  for(key in arrayObjects[i]) {      
    
      if (key == "status" && arrayObjects[i][key] == "good") {
        
          console.log(key + "->" + arrayObjects[i][key]);
      }else{
          console.log("nothing found");
      }
   }
}

#23


2  

In ES6 we have well-known symbols to expose some previously internal methods, you can use it to define how iterators work for this object:

在ES6中,我们有一些众所周知的符号来公开以前的内部方法,您可以使用它来定义迭代器如何为这个对象工作:

var p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3",
    *[Symbol.iterator]() {
        yield *Object.keys(this);
    }
};

[...p] //["p1", "p2", "p3"]

this will give the same result as using for...in es6 loop.

这将给出与使用相同的结果。在es6循环。

for(var key in p) {
    console.log(key);
}

But its important to know the capabilities you now have using es6!

但是了解您现在使用es6的功能是很重要的!

#24


2  

An object becomes an iterator when it implements the .next() method

对象在实现.next()方法时成为迭代器。

const james = {
name: 'James',
height: `5'10"`,
weight: 185,

[Symbol.iterator]() {
let properties = []
for (let key of Object.keys(james)){
     properties.push(key);
 }

index = 0;
return {
        next: () => {
            let key = properties[index];
            let value = this[key];
            let done = index >= properties.length - 1 ;
            index++;
            return { key, value, done };
        }
    };
  }

};


const iterator = james[Symbol.iterator]();

console.log(iterator.next().value); // 'James'
console.log(iterator.next().value); // `5'10`
console.log(iterator.next().value); // 185

#25


0  

I had a similar problem when using Angular, here is the solution that I've found.

我在使用角的时候遇到过类似的问题,这是我找到的解。

Step 1. Get all the object keys. using Object.keys. This method returns an array of a given object’s own enumerable properties.

步骤1。获取所有对象键。用种。此方法返回给定对象自己的可枚举属性的数组。

Step 2. Create an empty array. This is an where all the properties are going to live, since your new ngFor loop is going to point to this array, we gotta catch them all. Step 3. Iterate throw all keys, and push each one into the array you created. Here’s how that looks like in code.

步骤2。创建一个空数组。这是一个所有属性都将存在的地方,因为你的ngFor循环将指向这个数组,我们必须捕获它们。步骤3。迭代抛出所有键,并将每个键推入所创建的数组中。代码中是这样的。

    // Evil response in a variable. Here are all my vehicles.
let evilResponse = { 
  "car" : 
    { 
       "color" : "red",
       "model" : "2013"
    },
   "motorcycle": 
    { 
       "color" : "red",
       "model" : "2016"
    },
   "bicycle": 
    { 
       "color" : "red",
       "model" : "2011"
    }
}
// Step 1. Get all the object keys.
let evilResponseProps = Object.keys(evilResponse);
// Step 2. Create an empty array.
let goodResponse = [];
// Step 3. Iterate throw all keys.
for (prop of evilResponseProps) { 
    goodResponse.push(evilResponseProps[prop]);
}

Here is a link to the original post. https://medium.com/@papaponmx/looping-over-object-properties-with-ngfor-in-angular-869cd7b2ddcc

这是原始帖子的链接。https://medium.com/@papaponmx循环-在-对象-属性-与- ngfor -角- 869 - cd7b2ddcc

#26


0  

If you want to iterate only over properties use one of the answers above, however if you want to iterate over everything including functions, then you might want to use Object.getOwnPropertyNames(obj)

如果您只想对属性进行迭代,请使用上面的一个答案,但是如果您想对包括函数在内的所有内容进行迭代,那么您可能需要使用Object.getOwnPropertyNames(obj)

for (let o of Object.getOwnPropertyNames(Math)) {
  console.log(o);
}

I sometimes use this to fast test all functions on objects with simple inputs and outputs.

我有时用它快速测试对象上的所有函数,只要输入和输出很简单。

#27


-1  

  • single level indent
  • 单级缩进
  • single set of brackets
  • 一组括号
  • highest browser compatibility
  • 最高的浏览器兼容性
  • hasOwnProperty safe
  • hasOwnProperty安全

var p = {"p1": "value1", "p2": "value2", "p3": "value3"};

for (var key in p) if (p.hasOwnProperty(key)) {
  var value = p[key];
  console.log(key, value);
}

#28


-2  

Since ES2015 you can use the for of loop, to access the element directly:

自ES2015以来,可以使用for of loop直接访问元素:

// before ES2015
for(var key of elements){
  console.log(elements[key]);
}


// ES2015
for(let element of elements){
  console.log(element);
}

Hope this helps someone.

希望这可以帮助别人。

#29


-5  

Besause the asker's ['ultimate goal is to loop through some key value pairs'] and finally don't looking for a loop.

因为asker的['终极目标是遍历一些键值对']最终不寻找循环。

var p ={"p1":"value1","p2":"value2","p3":"value3"};
if('p1' in p){
  var val=p['p1'];
  ...
}

#1


3408  

You can use the for-in loop as shown by others. However, you also have to make sure that the key you get is an actual property of an object, and doesn't come from the prototype.

您可以像其他人一样使用forin循环。但是,您还必须确保获得的键是对象的实际属性,而不是来自原型。

Here is the snippet:

这是代码片段:

var p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3"
};

for (var key in p) {
    if (p.hasOwnProperty(key)) {
        console.log(key + " -> " + p[key]);
    }
}

#2


599  

Under ECMAScript 5, you can combine Object.keys() and Array.prototype.forEach():

在ECMAScript 5下,您可以将Object.keys()和Array.prototype.forEach()组合在一起:

var obj = { first: "John", last: "Doe" };

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

ES6 adds for...of:

对…的ES6补充说:

for (const key of Object.keys(obj)) {
    console.log(key, obj[key]);
}

ES2017 adds Object.entries() which avoids having to look up each value in the original object:

ES2017增加object .entries(),避免了查询原始对象中的每个值:

Object.entries(obj).forEach(
    ([key, value]) => console.log(key, value)
);

Both Object.keys() and Object.entries() iterate properties in the same order as a for...in loop but ignore the prototype chain. Only the object's own enumerable properties are iterated.

Object.keys()和Object.entries()都以与for相同的顺序迭代属性。在循环中,但忽略原型链。只迭代对象自己的可枚举属性。

Edit: ES2016 → ES6

编辑:ES2016→ES6

#3


298  

You have to use the for-in loop

你必须使用forin循环

But be very careful when using this kind of loop, because this will loop all the properties along the prototype chain.

但是在使用这种循环时要非常小心,因为这会沿着原型链循环所有的属性。

Therefore, when using for-in loops, always make use of the hasOwnProperty method to determine if the current property in iteration is really a property of the object you're checking on:

因此,在使用forin循环时,一定要使用hasOwnProperty方法来确定迭代中的当前属性是否真的是要检查的对象的属性:

for (var prop in p) {
    if (!p.hasOwnProperty(prop)) {
        //The current property is not a direct property of p
        continue;
    }
    //Do your logic with the property here
}

#4


230  

The question won't be complete if we don't mention about alternative methods for looping through objects.

如果我们不提及循环遍历对象的替代方法,那么这个问题就不会完整。

Nowadays many well known JavaScript libraries provide their own methods for iterating over collections, i.e. over arrays, objects, and array-like objects. These methods are convenient to use and are entirely compatible with any browser.

现在许多著名的JavaScript库都提供了自己的方法来遍历集合,比如遍历数组、对象和类数组的对象。这些方法使用起来很方便,并且与任何浏览器都完全兼容。

  1. If you work with jQuery, you may use jQuery.each() method. It can be used to seamlessly iterate over both objects and arrays:

    如果使用jQuery,可以使用jQuery.each()方法。它可以用来无缝地遍历对象和数组:

    $.each(obj, function(key, value) {
        console.log(key, value);
    });
    
  2. In Underscore.js you can find method _.each(), which iterates over a list of elements, yielding each in turn to a supplied function (pay attention to the order of arguments in iteratee function!):

    在强调。您可以找到method _.each(),它遍历一个元素列表,依次将每个元素转换为一个提供的函数(请注意iteratee函数中的参数顺序!)

    _.each(obj, function(value, key) {
        console.log(key, value);
    });
    
  3. Lo-Dash provides several methods for iterating over object properties. Basic _.forEach() (or it's alias _.each()) is useful for looping through both objects and arrays, however (!) objects with length property are treated like arrays, and to avoid this behavior it is suggested to use _.forIn() and _.forOwn() methods (these also have value argument coming first):

    Lo-Dash提供了几种迭代对象属性的方法。基本的_.forEach()(或者它的别名_.each()))对于遍历对象和数组都是有用的,但是(!)具有长度属性的对象被视为数组,为了避免这种行为,建议使用_.forIn()和_.forOwn()方法(这些方法也首先有值参数):

    _.forIn(obj, function(value, key) {
        console.log(key, value);
    });
    

    _.forIn() iterates over own and inherited enumerable properties of an object, while _.forOwn() iterates only over own properties of an object (basically checking against hasOwnProperty function). For simple objects and object literals any of these methods will work fine.

    _.forIn()迭代一个对象的自己和继承的可枚举属性,而_.forOwn()只迭代一个对象的自己的属性(基本上是检查hasOwnProperty函数)。对于简单的对象和对象文本,任何这些方法都可以正常工作。

Generally all described methods have the same behaviour with any supplied objects. Besides using native for..in loop will usually be faster than any abstraction, such as jQuery.each(), these methods are considerably easier to use, require less coding and provide better error handling.

通常,所有描述的方法与任何提供的对象具有相同的行为。除了使用本机的. .在loop中,通常比任何抽象(如jQuery.each()))都要快,这些方法非常容易使用,需要更少的编码,并提供更好的错误处理。

#5


46  

In ECMAScript 5 you have new approach in iteration fields of literal - Object.keys

在ECMAScript 5中,您在文本- Object.keys的迭代字段中有了新的方法

More information you can see on MDN

您可以在MDN上看到更多的信息。

My choice is below as a faster solution in current versions of browsers (Chrome30, IE10, FF25)

我的选择如下,作为当前版本浏览器中更快的解决方案(Chrome30, IE10, FF25)

var keys = Object.keys(p),
    len = keys.length,
    i = 0,
    prop,
    value;
while (i < len) {
    prop = keys[i];
    value = p[prop];
    i += 1;
}

You can compare performance of this approach with different implementations on jsperf.com:

您可以将这种方法的性能与jsperf.com上的不同实现进行比较:

Browser support you can see on Kangax's compat table

您可以在Kangax的compat表上看到对浏览器的支持

For old browser you have simple and full polyfill

对于旧的浏览器,你有简单和完整的polyfill

UPD:

乌利希期刊指南:

performance comparison for all most popular cases in this question on perfjs.info:

在这个问题上的性能比较:

object literal iteration

对象字面量迭代

#6


29  

You can just iterate over it like:

你可以这样迭代它:

for (var key in p) {
  alert(p[key]);
}

Note that key will not take on the value of the property, it's just an index value.

注意这个键不会取属性的值,它只是一个索引值。

#7


23  

Since es2015 is getting more and more popular I am posting this answer which include usage of generator and iterator to smoothly iterate through [key, value] pairs. As it is possible in other languages for instance Ruby.

由于es2015越来越受欢迎,所以我发布了这个答案,包括使用生成器和迭代器来平滑地迭代[key, value]对。就像在其他语言中一样,例如Ruby。

Ok here is a code:

这里有一个代码:

const MyObject = {
  'a': 'Hello',
  'b': 'it\'s',
  'c': 'me',
  'd': 'you',
  'e': 'looking',
  'f': 'for',
  [Symbol.iterator]: function* () {
    for (const i of Object.keys(this)) {
      yield [i, this[i]];
    }
  }
};

for (const [k, v] of MyObject) {
  console.log(`Here is key ${k} and here is value ${v}`);
}

All information about how can you do an iterator and generator you can find at developer Mozilla page.

关于如何进行迭代器和生成器的所有信息都可以在developer Mozilla页面找到。

Hope It helped someone.

希望它帮助某人。

EDIT:

编辑:

ES2017 will include Object.entries which will make iterating over [key, value] pairs in objects even more easier. It is now known that it will be a part of a standard according to the ts39 stage information.

ES2017将包括对象。在对象中迭代[键,值]对的条目更加容易。根据ts39阶段信息,它将成为标准的一部分。

I think it is time to update my answer to let it became even more fresher than it's now.

我认为是时候更新我的答案了,让它变得比现在更新鲜。

const MyObject = {
  'a': 'Hello',
  'b': 'it\'s',
  'c': 'me',
  'd': 'you',
  'e': 'looking',
  'f': 'for',
};

for (const [k, v] of Object.entries(MyObject)) {
  console.log(`Here is key ${k} and here is value ${v}`);
}

You can find more about usage on MDN page

您可以在MDN页面上找到更多关于用法的信息

#8


17  

via prototype with forEach() which should skip the prototype chain properties:

通过与forEach()的原型,可以跳过原型链属性:

Object.prototype.each = function(f) {
    var obj = this
    Object.keys(obj).forEach( function(key) { 
        f( key , obj[key] ) 
    });
}


//print all keys and values
var obj = {a:1,b:2,c:3}
obj.each(function(key,value) { console.log(key + " " + value) });
// a 1
// b 2
// c 3

#9


14  

After looking through all the answers in here, hasOwnProperty isn't required for my own usage because my json object is clean; there's really no sense in adding any additional javascript processing. This is all I'm using:

在查看了这里的所有答案之后,我自己的使用不需要hasOwnProperty,因为我的json对象是干净的;添加任何额外的javascript处理是没有意义的。这就是我所使用的:

for (var key in p) {
    console.log(key + ' => ' + p[key]);
    // key is key
    // value is p[key]
}

#10


13  

for(key in p) {
  alert( p[key] );
}

Note: you can do this over arrays, but you'll iterate over the length and other properties, too.

注意:可以对数组执行此操作,但也会对长度和其他属性进行迭代。

#11


12  

Object.keys(obj) : Array

种(obj):数组

retrieves all string-valued keys of all enumerable own (non-inherited) properties.

检索所有可枚举自身(非继承)属性的所有字符串值键。

So it gives the same list of keys as you intend by testing each object key with hasOwnProperty. You don't need that extra test operation than and Object.keys( obj ).forEach(function( key ){}) is supposed to be faster. Let's prove it:

因此,它通过使用hasOwnProperty测试每个对象键,给出与您希望的相同的键列表。您不需要额外的测试操作than和Object。键(obj)。对于每一个(函数(键){})都应该更快。让我们证明了这一点:

var uniqid = function(){
			var text = "",
					i = 0,
					possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
			for( ; i < 32; i++ ) {
					text += possible.charAt( Math.floor( Math.random() * possible.length ) );
			}
			return text;
		}, 
		CYCLES = 100000,
		obj = {}, 
		p1,
		p2,
		p3,
		key;

// Populate object with random properties
Array.apply( null, Array( CYCLES ) ).forEach(function(){
	obj[ uniqid() ] = new Date()
});

// Approach #1
p1 = performance.now();
Object.keys( obj ).forEach(function( key ){
	var waste = obj[ key ];
});

p2 = performance.now();
console.log( "Object.keys approach took " + (p2 - p1) + " milliseconds.");

// Approach #2
for( key in obj ) {
	if ( obj.hasOwnProperty( key ) ) {
		var waste = obj[ key ];
	}
}

p3 = performance.now();
console.log( "for...in/hasOwnProperty approach took " + (p3 - p2) + " milliseconds.");

In my Firefox I have following results

在我的Firefox中,我有如下的结果。

  • Object.keys approach took 40.21101451665163 milliseconds.
  • 对象。key方法花费了40.21101451665163毫秒。
  • for...in/hasOwnProperty approach took 98.26163508463651 milliseconds.
  • 为…in/hasOwnProperty方法耗时98.263508463651毫秒。

PS. on Chrome the difference even bigger http://codepen.io/dsheiko/pen/JdrqXa

Chrome上的差异更大http://codepen.io/dsheiko/pen/JdrqXa

PS2: In ES6 (EcmaScript 2015) you can iterate iterable object nicer:

PS2:在ES6 (EcmaScript 2015)中,您可以更好地迭代可迭代对象:

let map = new Map().set('a', 1).set('b', 2);
for (let pair of map) {
    console.log(pair);
}

// OR 
let map = new Map([
    [false, 'no'],
    [true,  'yes'],
]);
map.forEach((value, key) => {
    console.log(key, value);
});

#12


11  

It's interesting people in these answers have touched on both Object.keys() and for...of but never combined them:

有趣的是,在这些答案中,人们同时涉及了Object.keys()和for…但从未将它们结合在一起:

var map = {well:'hello', there:'!'};
for (let key of Object.keys(map))
    console.log(key + ':' + map[key]);

You can't just for...of an Object because it's not an iterator, and for...index or .forEach()ing the Object.keys() is ugly/inefficient.
I'm glad most people are refraining from for...in (with or without checking .hasOwnProperty()) as that's also a bit messy, so other than my answer above, I'm here to say...

你不能只是为了…一个对象,因为它不是迭代器,而且。对Object.keys()进行索引或. foreach()是丑陋的/低效的。我很高兴大多数人不喜欢……in (with or without check .hasOwnProperty()))因为它也有点混乱,所以除了我上面的答案之外,我要说的是……


You can make ordinary object associations iterate! Behaving just like Maps with direct use of the fancy for...of
DEMO working in Chrome and FF (I assume ES6 only)

您可以使普通对象关联迭代!表现得就像地图一样,直接运用想象力……在Chrome和FF中工作的演示(我假设只有ES6)

var ordinaryObject = {well:'hello', there:'!'};
for (let pair of ordinaryObject)
    //key:value
    console.log(pair[0] + ':' + pair[1]);

//or
for (let [key, value] of ordinaryObject)
    console.log(key + ':' + value);

So long as you include my shim below:

只要你在下面写上我的名字:

//makes all objects iterable just like Maps!!! YAY
//iterates over Object.keys() (which already ignores prototype chain for us)
Object.prototype[Symbol.iterator] = function() {
    var keys = Object.keys(this)[Symbol.iterator]();
    var obj = this;
    var output;
    return {next:function() {
        if (!(output = keys.next()).done)
            output.value = [output.value, obj[output.value]];
        return output;
    }};
};

Without having to create a real Map object that doesn't have the nice syntactic sugar.

不需要创建一个真正的映射对象它没有很好的语法糖。

var trueMap = new Map([['well', 'hello'], ['there', '!']]);
for (let pair of trueMap)
    console.log(pair[0] + ':' + pair[1]);

In fact, with this shim, if you still wanted to take advantage of Map's other functionality (without shimming them all in) but still wanted to use the neat object notation, since objects are now iterable you can now just make a Map from it!

实际上,有了这个shim,如果您还想利用Map的其他功能(不需要将它们全部填满),但是仍然想使用整洁的对象表示法,因为对象现在是可迭代的,现在您可以从它创建一个映射!

//shown in demo
var realMap = new Map({well:'hello', there:'!'});

For those who don't like to shim, or mess with prototype in general, feel free to make the function on window instead, calling it something like getObjIterator() then;

对于那些不喜欢shim的人,或者一般的原型,可以*地在窗口中创建函数,然后调用getObjIterator();

//no prototype manipulation
function getObjIterator(obj) {
    //create a dummy object instead of adding functionality to all objects
    var iterator = new Object();

    //give it what the shim does but as its own local property
    iterator[Symbol.iterator] = function() {
        var keys = Object.keys(obj)[Symbol.iterator]();
        var output;

        return {next:function() {
            if (!(output = keys.next()).done)
                output.value = [output.value, obj[output.value]];
            return output;
        }};
    };

    return iterator;
}

Now you can just call it as an ordinary function, nothing else is affected

现在你可以把它称为一个普通的函数,其他的都不受影响。

var realMap = new Map(getObjIterator({well:'hello', there:'!'}))

or

for (let pair of getObjIterator(ordinaryObject))

There's no reason why that wouldn't work.

没有理由说这行不通。

Welcome to the future.

欢迎来到未来。

#13


7  

You can add a simple forEach function to all objects, so you can automatically loop through any object:

您可以为所有对象添加一个简单的forEach函数,因此您可以自动循环遍历任何对象:

Object.defineProperty(Object.prototype, 'forEach', {
    value: function (func) {
        for (var key in this) {
            if (!this.hasOwnProperty(key)) {
                // skip loop if the property is from prototype
                continue;
            }
            var value = this[key];
            func(key, value);
        }
    },
    enumerable: false
});

For those people who don't like the "for ... in"-method:

对于那些不喜欢“For…”的人在“方法:

Object.defineProperty(Object.prototype, 'forEach', {
    value: function (func) {
        var arr = Object.keys(this);
        for (var i = 0; i < arr.length; i++) {
            var key = arr[i];
            func(key, this[key]);
        }
    },
    enumerable: false
});

Now, you can simple call:

现在,你可以简单地调用:

p.forEach (function(key, value){
    console.log ("Key: " + key);
    console.log ("Value: " + value);
});

If you don't want to get conflicts with other forEach-Methods you can name it with your unique name.

如果您不想与其他foreacher方法发生冲突,您可以使用您的惟一名称来命名它。

#14


7  

The Object.keys() method returns an array of a given object's own enumerable properties. Read more about it here

方法的作用是:返回给定对象自己的可枚举属性的数组。在这里阅读更多

var p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3"
};

Object.keys(p).map((key)=> console.log(key + "->" + p[key]))

#15


7  

Here is another method to iterate through an object.

这是另一个遍历对象的方法。

   var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};


Object.keys(p).forEach(key => { console.log(key, p[key]) })

#16


7  

var p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3"
};

for (var key in p) {
    if (p.hasOwnProperty(key)) {
        console.log(key + " = " + p[key]);
    }
}
<p>
  Output:<br>
  p1 = values1<br>
  p2 = values2<br>
  p3 = values3
</p>

#17


5  

Only JavaScript code without dependencies:

只有没有依赖项的JavaScript代码:

var p = {"p1": "value1", "p2": "value2", "p3": "value3"};
keys = Object.keys(p);   // ["p1", "p2", "p3"]

for(i = 0; i < keys.length; i++){
  console.log(keys[i] + "=" + p[keys[i]]);   // p1=value1, p2=value2, p3=value3
}

#18


5  

Loops can be pretty interesting when using pure JavaScript. It seems that only ECMA6 (New 2015 JavaScript specification) got the loops under control. Unfortunately as I'm writing this, both Browsers and popular Integrated development environment (IDE) are still struggling to support completely the new bells and whistles.

当使用纯JavaScript时,循环会非常有趣。似乎只有ECMA6(新的2015 JavaScript规范)控制了循环。不幸的是,当我写这篇文章的时候,浏览器和流行的集成开发环境(IDE)仍然很难完全支持新的功能。

At a glance here is what a JavaScript object loop look like before ECMA6:

这是JavaScript对象循环在ECMA6之前的样子:

for (var key in object) {
  if (p.hasOwnProperty(key)) {
    var value = object[key];
    console.log(key); // This is the key;
    console.log(value); // This is the value;
  }
}

Also, I know this is out of scope with this question but in 2011, ECMAScript 5.1 added the forEach method for Arrays only which basically created a new improved way to loop through arrays while still leaving non iterable objects with the old verbose and confusing for loop. But the odd part is that this new forEach method does not support break which led to all sorts of other problems.

而且,我知道这个问题超出了范围,但是在2011年,ECMAScript 5.1只为数组添加了forEach方法,它基本上创建了一种新的改进方法来循环数组,同时仍然保留不可迭代的对象,使之具有原来的冗长和混乱的for循环。但奇怪的是,这种新的forEach方法不支持中断,这导致了其他各种问题。

Basically in 2011, there is not a real solid way to loop in JavaScript other than what many popular libraries (jQuery, Underscore, etc.) decided to re-implement.

基本上,在2011年,除了许多流行的库(jQuery、下线等)决定重新实现之外,没有一种真正可靠的方法来循环使用JavaScript。

As of 2015, we now have a better out of the box way to loop (and break) any object type (including Arrays and Strings). Here is what a loop in JavaScript will eventually look like when the recommendation becomes mainstream:

到2015年,我们现在有了更好的方法来循环(和中断)任何对象类型(包括数组和字符串)。下面是JavaScript的一个循环,当建议成为主流时,它最终会变成:

for (let [key, value] of Object.entries(object)) {
    console.log(key); // This is the key;
    console.log(value); // This is the value;
}

Note that most browsers won't support the code above as of June 18th 2016. Even in Chrome you need to enable this special flag for it to work: chrome://flags/#enable-javascript-harmony

请注意,到2016年6月18日,大多数浏览器都不支持上述代码。即使是在Chrome中,也需要启用这个特殊的标志:Chrome:/ flags/#启用javascript-harmony

Until this becomes the new standard, the old method can still be used but there are also alternatives in popular libraries or even lightweight alternatives for those who aren't using any of these libraries.

在这成为新的标准之前,旧的方法仍然可以使用,但是在流行的库中还有其他的替代方法,甚至是那些没有使用这些库的人的轻量级替代方案。

#19


4  

I would do this rather than checking obj.hasOwnerProperty within every for ... in loop.

我会这样做,而不是检查obj。每个人拥有的财产……在循环。

var obj = {a : 1};
for(var key in obj){
    //obj.hasOwnProperty(key) is not needed.
    console.log(key);
}
//then check if anybody has messed the native object. Put this code at the end of the page.
for(var key in Object){
    throw new Error("Please don't extend the native object");
}

#20


3  

If you want to iterate over non-enumerable properties as well, you can use Object.getOwnPropertyNames(obj) to return an array of all properties (enumerable or not) found directly upon a given object.

如果您也想遍历非可枚举属性,那么可以使用object. getownpropertynames (obj)来返回直接在给定对象上找到的所有属性(可枚举或非枚举)的数组。

var obj = Object.create({}, {
  // non-enumerable property
  getFoo: {
    value: function() { return this.foo; },
    enumerable: false
  }
});

obj.foo = 1; // enumerable property

Object.getOwnPropertyNames(obj).forEach(function (name) {
  document.write(name + ': ' + obj[name] + '<br/>');
});

#21


3  

Considering ES6 I'd like to add my own spoon of sugar and provide one more approach to iterate over object's properties.

考虑到ES6,我想添加我自己的一勺糖,并提供一种方法来迭代对象的属性。

Since plain JS object isn't iterable just out of box, we aren't able to use for..of loop for iterating over its content. But no one can stop us to make it iterable.

因为普通的JS对象并不是开箱即用的,所以我们不能用for..。循环遍历它的内容。但是没有人能阻止我们使它可迭代。

Let's we have book object.

我们有book object。

let book = {
  title: "Amazing book",
  author: "Me",
  pages: 3
}

book[Symbol.iterator] = function(){

  let properties = Object.keys(this); // returns an array with property names
  let counter = 0;
  let isDone = false;

  let next = () => {
    if(counter >= properties.length){
      isDone = true;
    }
    return { done: isDone, value: this[properties[counter++]] }
  }

  return { next };
}

Since we've made it we can use it this way:

既然我们已经成功了,我们可以这样使用它:

for(let pValue of book){
  console.log(pValue);
}
------------------------
Amazing book
Me
3

Or if you know the power of ES6 generators, so you certainly can make the code above much shorter.

或者如果您知道ES6生成器的功能,那么您当然可以使上面的代码更短。

book[Symbol.iterator] = function *(){

  let properties = Object.keys(this);
  for (let p of properties){
    yield this[p];
  }

}

Sure, you can apply such behavior for all objects with making Object iterable on prototype level.

当然,您可以对所有对象应用这种行为,使对象在原型级上可迭代。

Object.prototype[Symbol.iterator] = function() {...}

Also, objects that comply with the iterable protocol can be used with the new ES2015 feature spread operator thus we can read object property values as an array.

同样,符合iterable协议的对象可以与新的ES2015特性扩展操作符一起使用,这样我们就可以将对象属性值读取为一个数组。

let pValues = [...book];
console.log(pValues);
-------------------------
["Amazing book", "Me", 3]

Or you can use destructuring assignment:

或者你可以使用析构赋值:

let [title, , pages] = book; // notice that we can just skip unnecessary values
console.log(title);
console.log(pages);
------------------
Amazing book
3

You can check out JSFiddle with all code I've provided above.

您可以检查JSFiddle是否包含我上面提供的所有代码。

#22


2  

If anybody needs to loop through arrayObjects with condition:

如果有人需要对arrayObjects进行循环

var arrayObjects = [{"building":"A", "status":"good"},{"building":"B","status":"horrible"}];

for (var i=0; i< arrayObjects.length; i++) {
  console.log(arrayObjects[i]);
  
  for(key in arrayObjects[i]) {      
    
      if (key == "status" && arrayObjects[i][key] == "good") {
        
          console.log(key + "->" + arrayObjects[i][key]);
      }else{
          console.log("nothing found");
      }
   }
}

#23


2  

In ES6 we have well-known symbols to expose some previously internal methods, you can use it to define how iterators work for this object:

在ES6中,我们有一些众所周知的符号来公开以前的内部方法,您可以使用它来定义迭代器如何为这个对象工作:

var p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3",
    *[Symbol.iterator]() {
        yield *Object.keys(this);
    }
};

[...p] //["p1", "p2", "p3"]

this will give the same result as using for...in es6 loop.

这将给出与使用相同的结果。在es6循环。

for(var key in p) {
    console.log(key);
}

But its important to know the capabilities you now have using es6!

但是了解您现在使用es6的功能是很重要的!

#24


2  

An object becomes an iterator when it implements the .next() method

对象在实现.next()方法时成为迭代器。

const james = {
name: 'James',
height: `5'10"`,
weight: 185,

[Symbol.iterator]() {
let properties = []
for (let key of Object.keys(james)){
     properties.push(key);
 }

index = 0;
return {
        next: () => {
            let key = properties[index];
            let value = this[key];
            let done = index >= properties.length - 1 ;
            index++;
            return { key, value, done };
        }
    };
  }

};


const iterator = james[Symbol.iterator]();

console.log(iterator.next().value); // 'James'
console.log(iterator.next().value); // `5'10`
console.log(iterator.next().value); // 185

#25


0  

I had a similar problem when using Angular, here is the solution that I've found.

我在使用角的时候遇到过类似的问题,这是我找到的解。

Step 1. Get all the object keys. using Object.keys. This method returns an array of a given object’s own enumerable properties.

步骤1。获取所有对象键。用种。此方法返回给定对象自己的可枚举属性的数组。

Step 2. Create an empty array. This is an where all the properties are going to live, since your new ngFor loop is going to point to this array, we gotta catch them all. Step 3. Iterate throw all keys, and push each one into the array you created. Here’s how that looks like in code.

步骤2。创建一个空数组。这是一个所有属性都将存在的地方,因为你的ngFor循环将指向这个数组,我们必须捕获它们。步骤3。迭代抛出所有键,并将每个键推入所创建的数组中。代码中是这样的。

    // Evil response in a variable. Here are all my vehicles.
let evilResponse = { 
  "car" : 
    { 
       "color" : "red",
       "model" : "2013"
    },
   "motorcycle": 
    { 
       "color" : "red",
       "model" : "2016"
    },
   "bicycle": 
    { 
       "color" : "red",
       "model" : "2011"
    }
}
// Step 1. Get all the object keys.
let evilResponseProps = Object.keys(evilResponse);
// Step 2. Create an empty array.
let goodResponse = [];
// Step 3. Iterate throw all keys.
for (prop of evilResponseProps) { 
    goodResponse.push(evilResponseProps[prop]);
}

Here is a link to the original post. https://medium.com/@papaponmx/looping-over-object-properties-with-ngfor-in-angular-869cd7b2ddcc

这是原始帖子的链接。https://medium.com/@papaponmx循环-在-对象-属性-与- ngfor -角- 869 - cd7b2ddcc

#26


0  

If you want to iterate only over properties use one of the answers above, however if you want to iterate over everything including functions, then you might want to use Object.getOwnPropertyNames(obj)

如果您只想对属性进行迭代,请使用上面的一个答案,但是如果您想对包括函数在内的所有内容进行迭代,那么您可能需要使用Object.getOwnPropertyNames(obj)

for (let o of Object.getOwnPropertyNames(Math)) {
  console.log(o);
}

I sometimes use this to fast test all functions on objects with simple inputs and outputs.

我有时用它快速测试对象上的所有函数,只要输入和输出很简单。

#27


-1  

  • single level indent
  • 单级缩进
  • single set of brackets
  • 一组括号
  • highest browser compatibility
  • 最高的浏览器兼容性
  • hasOwnProperty safe
  • hasOwnProperty安全

var p = {"p1": "value1", "p2": "value2", "p3": "value3"};

for (var key in p) if (p.hasOwnProperty(key)) {
  var value = p[key];
  console.log(key, value);
}

#28


-2  

Since ES2015 you can use the for of loop, to access the element directly:

自ES2015以来,可以使用for of loop直接访问元素:

// before ES2015
for(var key of elements){
  console.log(elements[key]);
}


// ES2015
for(let element of elements){
  console.log(element);
}

Hope this helps someone.

希望这可以帮助别人。

#29


-5  

Besause the asker's ['ultimate goal is to loop through some key value pairs'] and finally don't looking for a loop.

因为asker的['终极目标是遍历一些键值对']最终不寻找循环。

var p ={"p1":"value1","p2":"value2","p3":"value3"};
if('p1' in p){
  var val=p['p1'];
  ...
}