Traverse through Javascript object properties

前端 未结 8 1680
清酒与你
清酒与你 2021-01-31 01:48

I want to traverse through JavaScript object\'s property

    var obj =
    {
        a: \'value1\',
        b: \'value2\',
        c: \'value3\',
        d: \'va         


        
相关标签:
8条回答
  • 2021-01-31 02:25

    Here is how it is done using the ES5 - Object.keys() :

    Object.keys(obj).forEach(function(key, idx) {
       ...
    }); 
    

    http://jsfiddle.net/magiccrafter/bvwenh5d/

    Mozilla's docs: link

    0 讨论(0)
  • 2021-01-31 02:33

    prop will reference the property name, not its value.

    for (var prop in obj) {
        obj[prop] = 'xxx';
    }
    

    Construct documentation.

    Also you may want to check if the property belongs to the object using hasOwnProperty. It may happen that someone adds properties to the prototype and those are also iterated by for ... in.

    0 讨论(0)
提交回复
热议问题