I have a javascript object like this let Lila = { name: 'Lila', height:
5'10",
weight: 185}
I want to iterate it using next()
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; }
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;
}
};
}
};
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]) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With