Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make iterable object in Javascript

I have a javascript object like this let Lila = { name: 'Lila', height:5'10", weight: 185} I want to iterate it using next()

like image 632
Fatima Hossny Avatar asked Jan 06 '18 21:01

Fatima Hossny


3 Answers

You could assign a Symbol.iterator property to the object with an iterator.

Read more about the use of iterator.next in iteration protocols.

let lila = { name: 'Lila', height: '5\'10"', weight: 185 };

lila[Symbol.iterator] = function* () {
    var k;
    for (k in this) {
        yield [k, this[k]];
    }
};

var iterator = lila[Symbol.iterator]();

console.log(iterator.next()); // get the first of a sequence of values

console.log([...lila]);       // get all key/values pairs
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 61
Nina Scholz Avatar answered Sep 24 '22 20:09

Nina Scholz


here is the answer

const Lila = {
    name: 'Lila',
    height: `5'10"`,
    weight: 185,
    [Symbol.iterator]() {
        let index = 0; // use index to track properties 
        let properties = Object.keys(this); // get the properties of the object 
        let Done = false; // set to true when the loop is done 
        return { // return the next method, need for iterator 
            next: () => {
                Done = (index >= properties.length);
                // define the object you will return done state, value eg Lila ,key eg 
                //name
                let obj = {
                    done: Done,
                    value: this[properties[index]],
                    key: properties[index]
                };
                index++; // increment index
                return obj;
            }
        };
    }
};
like image 35
Fatima Hossny Avatar answered Sep 21 '22 20:09

Fatima Hossny


why do you need an iterator or a generator? Keep it simple and just iterate over the object...

const lila = { name: 'Lila', height: '5\'10"', weight: 185 };

for (key in lila) { console.log(lila[key]) }
like image 26
daino3 Avatar answered Sep 20 '22 20:09

daino3