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]) }
you can convert an object to an iterable (Array) with Object.entries
let Lila = {
name: 'Lila',
height: 5.10,
weight: 185
};
let iterableLila = Object.entries(Lila);
console.log(iterableLila);
You can iterate through an object's keys using Object.keys() and then just encapsulate it normally with an iterator function:
function makeIterator(obj) {
let keys = Object.keys(obj);
let current_index = 0;
return {
next: function() {
return current_index < keys.length ?
{value: obj[keys[current_index++]], done: false} :
{done: true};
}
};
}
then you can use it like that:
let Lila = { name: 'Lila', height:5'10",
weight: 185}
let iterator = makeIterator(Lila)
console.log(iterator.next().value)
console.log(iterator.next().value)
console.log(iterator.next().value)
Try following:
const lila = {
name: "lila",
height: "5'10",
weight: 185,
[Symbol.iterator] () {
let step = 0;
let properties = Object.keys(this);
return{
next(){
return{
value: properties[step],
done: step++ === properties.length
}
}
}
}
}for (let prop of lila){console.log(prop)}
Object.keys()