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

It's the for...in statement (MDN, ECMAScript spec).

You can read it as "FOR every property IN the obj object, assign each property to the PROPT variable in turn".

查看更多
泪湿衣
3楼-- · 2018-12-31 00:23
let obj = {"a": 3, "b": 2, "6": "a"}

Object.keys(obj).map((item) => {console.log("item", obj[item])})

// a
// 3
// 2
查看更多
伤终究还是伤i
4楼-- · 2018-12-31 00:23

Objects in JavaScript are collections of properties and can therefore be looped in a for each statement.

You should think of obj as an key value collection.

查看更多
呛了眼睛熬了心
5楼-- · 2018-12-31 00:23

To further refine the accepted answer it's worth noting that if you instantiate the object with a var object = Object.create(null) then object.hasOwnProperty(property) will trigger a TypeError. So to be on the safe side, you'd need to call it from the prototype like this:

for (var property in object) {
    if (Object.prototype.hasOwnProperty.call(object, property)) {
        // do stuff
    }
}
查看更多
呛了眼睛熬了心
6楼-- · 2018-12-31 00:25
Object.keys(obj).forEach(key =>
  console.log(`key=${key} value=${obj[key]}`)
);
查看更多
君临天下
7楼-- · 2018-12-31 00:25

Also adding the recursive way:

function iterate(obj) {
    // watch for objects we've already iterated so we won't end in endless cycle
    // for cases like var foo = {}; foo.bar = foo; iterate(foo);
    var walked = [];
    var stack = [{obj: obj, stack: ''}];
    while(stack.length > 0)
    {
        var item = stack.pop();
        var obj = item.obj;
        for (var property in obj) {
            if (obj.hasOwnProperty(property)) {
                if (typeof obj[property] == "object") {
                  // check if we haven't iterated through the reference yet
                  var alreadyFound = false;
                  for(var i = 0; i < walked.length; i++)
                  {
                    if (walked[i] === obj[property])
                    {
                      alreadyFound = true;
                      break;
                    }
                  }
                  // new object reference
                  if (!alreadyFound)
                  {
                    walked.push(obj[property]);
                    stack.push({obj: obj[property], stack: item.stack + '.' + property});
                  }
                }
                else
                {
                    console.log(item.stack + '.' + property + "=" + obj[property]);
                }
            }
        }
    }
}

Usage:

iterate({ foo: "foo", bar: { foo: "foo"} }); 
查看更多
登录 后发表回答