Loop through properties in JavaScript object with Lodash

后端 未结 7 1940
闹比i
闹比i 2021-02-01 00:01

Is it possible to loop through the properties in a JavaScript object? For instance, I have a JavaScript object defined as this:

myObject.options = {
  property1:         


        
7条回答
  •  别那么骄傲
    2021-02-01 00:48

    In ES6, it is also possible to iterate over the values of an object using the for..of loop. This doesn't work right out of the box for JavaScript objects, however, as you must define an @@iterator property on the object. This works as follows:

    • The for..of loop asks the "object to be iterated over" (let's call it obj1 for an iterator object. The loop iterates over obj1 by successively calling the next() method on the provided iterator object and using the returned value as the value for each iteration of the loop.
    • The iterator object is obtained by invoking the function defined in the @@iterator property, or Symbol.iterator property, of obj1. This is the function you must define yourself, and it should return an iterator object

    Here is an example:

    const obj1 = {
      a: 5,
      b: "hello",
      [Symbol.iterator]: function() {
        const thisObj = this;
        let index = 0;
        return {
          next() {
            let keys = Object.keys(thisObj);
            return {
              value: thisObj[keys[index++]],
              done: (index > keys.length)
            };
          }
        };
      }
    };
    

    Now we can use the for..of loop:

    for (val of obj1) {
      console.log(val);
    }    // 5 hello
    

提交回复
热议问题