Iterate through object properties

2018-12-31 00:17发布

 var obj = {
		name: "Simon",
		age: "20",
		clothing: {
			style: "simple",
			hipster: false
		}
	}

	for(var propt in obj){
		alert(propt + ': ' + obj[propt]);
	}

How does the variable propt represent the properties of the object? It's not a built-in method, or property. Then why does it come up with every property in the object?

25条回答
何处买醉
2楼-- · 2018-12-31 00:47

In upcoming versions of ES, you can use Object.entries:

for (const [key, value] of Object.entries(obj)) { }

or

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

If you just want to iterate over the values, then use Object.values:

for (const value of Object.values(obj)) { }

or

Object.values(obj).forEach(value => ...)
查看更多
登录 后发表回答