Nested for..of iterate over first array Element

Viewed 126

I have Data Structure like this

const array = [
  [["first_name" , "First"], ["image" , "image"]],
  [["email" , "email"]],
  [["last_name","last_name"]],
  [["password" , "password"], ["password", "password"]]
]

My Iterator Implementation is

let arr = array.values();
let obj = {
  [Symbol.iterator]: function () {
    return {
      next() {
        for (const iterator of arr) {
          for (let [, value] of iterator) {
            return {
              done: false,
              value,
            };
          }
        }

        return {
          done: true,
        };
      },
    };
  },
}

But when I iterate it [...obj]

I am getting Only first element of 2D array

The output I am getting is ["First" , "email" , "last_name" , "password"]

Expected output ["First" , "image" , "email" , "last_name" , "password", "password"]

Nested for..in iterate only 1st element of nested array

Note:- Above solution is working fine with Symbol.Iterator generator function

1 Answers

Like Nenad Vracar's answer, since it is returned from the inner for loop statement, it does not loop all the inner arrays, only the outer array loops and ends.

Individual states must be able to be saved to implement what you want with Symbol.iterator alone without using Generator.

const array = [
  [["first_name" , "First"], ["image" , "image"]],
  [["email" , "email"]],
  [["last_name","last_name"]],
  [["password" , "password"], ["password", "password"]]
];

const obj = {
  [Symbol.iterator]: () => {
    return {
      stack: [...array],
      target: [],
      next() {
        if (!this.target.length && !this.stack.length) return {
          done: true,
          value: undefined,
        }
        if (!this.target.length) this.target = this.stack.shift();

        return {
          done: false,
          value: this.target.shift()[1],
        };
      },
    }
  }
};

console.log([...obj]); // ['First', 'image', 'email', 'last_name', 'password', 'password']
Related