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:43

Iterating over properties requires this additional hasOwnProperty check:

for (var property in object) {
    if (object.hasOwnProperty(property)) {
        // do stuff
    }
}

It's necessary because an object's prototype contains additional properties for the object which are technically part of the object. These additional properties are inherited from the base object class, but are still properties of object.

hasOwnProperty simply checks to see if this is a property specific to this class, and not one inherited from the base class.

查看更多
零度萤火
3楼-- · 2018-12-31 00:43

Dominik's answer is perfect, I just prefer to do it that way, as it's cleaner to read:

for (var property in object) {
    if (!object.hasOwnProperty(property)) continue;

    // Do stuff...
}
查看更多
大哥的爱人
4楼-- · 2018-12-31 00:43

If running Node I'd recommend:

Object.keys(obj).forEach((key, index) => {
    console.log(key);
});
查看更多
若你有天会懂
5楼-- · 2018-12-31 00:44

Your for loop is iterating over all of the properties of the object obj. propt is defined in the first line of your for loop. It is a string that is a name of a property of the obj object. In the first iteration of the loop, propt would be "name".

查看更多
浪荡孟婆
6楼-- · 2018-12-31 00:45

Girls and guys we are in 2017 and we do not have that much time for typing... So lets do this cool new fancy ECMAScript 2016:

Object.keys(obj).forEach(e => console.log(`key=${e}  value=${obj[e]}`));
查看更多
ら面具成の殇う
7楼-- · 2018-12-31 00:46

What for..in loop does is that it creates a new variable (var someVariable) and then stores each property of the given object in this new variable(someVariable) one by one. Therefore if you use block {}, you can iterate. Consider the following example.

var obj = {
     name:'raman',
     hobby:'coding',
     planet:'earth'
     };

for(var someVariable in obj) {
  //do nothing..
}

console.log(someVariable); // outputs planet
查看更多
登录 后发表回答