Radek Anuszewski
Radek Anuszewski

Reputation: 1910

Javascript and Typescript: iteration over object with for..of

From ES6 iteration over object values I took a way of iteration over object values. Here's my implementation:

function* entries (obj): IterableIterator<any> {
    for (const key of Object.keys(obj)) {
        const value = obj[key];
        yield [
            key,
            value,
        ];
    }
}

Then I want to use that in render() React Component's method:

render () {
    const that = this;
    const newVar = (() => {
        const elements = [];
        for (const [key, value] of entries(that.filters)) {
            elements.push(<h2>{JSON.stringify(key)} {JSON.stringify(value)}</h2>);
        }
        return elements;

    })();
    return (
        <section>
            {newVar}
        </section>
    );
}

But if I debug this code with .map files in Chrome Developer console, newVar is an empty array. If I alert obj in entries generator I got proper object. Am I missing something really simple? Thank you in advance for every answer. I use Typescript with es5 option and I read that it supports generators: Generators and Iteration for ES5/ES3.

Upvotes: 0

Views: 443

Answers (1)

Bergi
Bergi

Reputation: 664777

I use Typescript with es5 option and I read that it supports generators: Generators and Iteration for ES5/ES3.

It also says that you need to use the --downlevelIteration flag for that. Otherwise it will still transpile for … of-loops into array iteration, which fails on iterables like your generator instance without a .length property.

Upvotes: 2

Related Questions