How do I access properties of a javascript object if I don't know the names?

前端 未结 8 1401
囚心锁ツ
囚心锁ツ 2020-11-28 18:49

Say you have a javascript object like this:

var data = { foo: \'bar\', baz: \'quux\' };

You can access the properties by the property name:

8条回答
  •  情深已故
    2020-11-28 19:11

    You can use Object.keys(), "which returns an array of a given object's own enumerable property names, in the same order as we get with a normal loop."

    You can use any object in place of stats:

    var stats = {
      a: 3,
      b: 6,
      d: 7,
      erijgolekngo: 35
    }
    /*  this is the answer here  */
    for (var key in Object.keys(stats)) {
      var t = Object.keys(stats)[key];
      console.log(t + " value =: " + stats[t]);
    }

提交回复
热议问题