Using Objects in For Of Loops

后端 未结 14 2001
春和景丽
春和景丽 2020-11-28 05:56

Why isn\'t is possible to use objects in for of loops? Or is this a browser bug? This code doesn\'t work in Chrome 42, saying undefined is not a function:

te         


        
相关标签:
14条回答
  • 2020-11-28 06:04

    If you are storing data in a key-value store, please use Map which is explicitly designed for this purpose.

    If you have to use an object though, ES2017 (ES8) allows you to use Object.values:

    const foo = { a: 'foo', z: 'bar', m: 'baz' };
    for (let value of Object.values(foo)) {
        console.log(value);
    }
    

    If that isn't supported yet, use a polyfill: Alternative version for Object.values()

    And finally if you're supporting an older environment that don't support this syntax, you'll have to resort to using forEach and Object.keys:

    var obj = { a: 'foo', z: 'bar', m: 'baz' };
    Object.keys(obj).forEach(function (prop) {
        var value = obj[prop];
        console.log(value);
    });
    
    0 讨论(0)
  • 2020-11-28 06:04

    Using Array Destruction you can iterate it as follows using forEach

    const obj = { a: 5, b: 7, c: 9 };
    
    Object.entries(obj).forEach(([key, value]) => {
      console.log(`${key} ${value}`); // "a 5", "b 7", "c 9"
    });
    
    0 讨论(0)
  • 2020-11-28 06:06

    I just did the following to easily console out my stuff.

    for (let key in obj) {
      if(obj.hasOwnProperty(key){
        console.log(`${key}: ${obj[key]}`);
      }
    }
    
    0 讨论(0)
  • 2020-11-28 06:07

    What about using

    function* entries(obj) {
        for (let key of Object.keys(obj)) {
            yield [key, obj[key]];
        }
    }
    
    for ([key, value] of entries({a: "1", b: "2"})) {
        console.log(key + " " + value);
    }
    
    0 讨论(0)
  • 2020-11-28 06:08

    How about using Object.keys to get an array of keys? And then forEach on the Array?

    obj = { a: 1, b:2}
    Object.keys(obj).forEach( key => console.log(`${key} => ${obj[key]}`))
    
    0 讨论(0)
  • 2020-11-28 06:13

    Object literals don't have built-in iterators, which are required to work with for...of loops. However, if you don't want to go thru the trouble of adding your own [Symbol.iterator] to your object, you can simply use the Object.keys() method. This method returns an Array object, which already has a built-in iterator, so you can use it with a for...of loop like this:

    const myObject = {
        country: "Canada",
        province: "Quebec",
        city: "Montreal"
    }
    
    for (let i of Object.keys(myObject)) {
        console.log("Key:", i, "| Value:", myObject[i]);
    }
    
    //Key: country | Value: Canada
    //Key: province | Value: Quebec
    //Key: city | Value: Montreal
    
    0 讨论(0)
提交回复
热议问题