Traverse through Javascript object properties

前端 未结 8 1679
清酒与你
清酒与你 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:10

    Using ecmascript2017: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

    const object1 = {
      a: 'somestring',
      b: 42
    };
    
    for (let [key, value] of Object.entries(object1)) {
      console.log(`${key}: ${value}`);
    }
    
    0 讨论(0)
  • 2021-01-31 02:11
    for(let i = 0; i < Object.entries(dog).length; i++){
      this.temp.push(Object.entries(dog)[i]);
    }
    
    0 讨论(0)
  • 2021-01-31 02:12

    If you're in an ES6 friendly environment, you can also try using the for...of loop which is closer to your original attempt.

    EDIT: As Caleb pointed out, for..of is specific to collections with the Symbol.iterator property (e.g. not standard JS objects).

    But I'm leaving this answer here in case anybody else finds it useful at some point to have it pointed out explicitly that a for..of is not a great solution here.

    let obj = {};
    
    for (let prop of obj) { // This will throw an error
        prop = 'xxx';
    }
    

    Reference: MDN - for...of

    0 讨论(0)
  • 2021-01-31 02:14
    const obj = {
    "abc":1, "def":2
    }
    for (let key in obj){
      console.log(key+":"+obj[key])
    }
    
    0 讨论(0)
  • 2021-01-31 02:14
    var temp= {"6s","vikash","500"};
    console.log([...temp]); //["6s","vikash","500"]
    
    0 讨论(0)
  • 2021-01-31 02:17

    You should check that the property belongs to the object and not a prototype.

    for (var prop in obj) {
        if (obj.hasOwnProperty(prop)) {
            obj[prop] = 'xxx';
        }
    }
    
    0 讨论(0)
提交回复
热议问题