forked from eggheadio-github/stack-overflow-copy-paste
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmakeObjectIterable.js
More file actions
32 lines (30 loc) · 808 Bytes
/
Copy pathmakeObjectIterable.js
File metadata and controls
32 lines (30 loc) · 808 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
export default makeObjectIterable
/**
* Original Source: https://stackoverflow.com/questions/48132121/how-to-make-iterable-object-in-javascript
*
* Makes a regular object iterable so that it can be used in constructs such
* as a for-of loop.
*
* @param {Object} obj - object on which iteration is desired
* @returns {Object} - returns the same object
*/
function makeObjectIterable(obj) {
Object.defineProperty(obj, Symbol.iterator, {
writable: false,
enumerable: false,
configurable: true,
value: function iteratorCreator() {
let idx = 0
const ks = Object.keys(obj)
return {
next: function nextElement() {
return {
value: obj[ks[idx++]],
done: idx > ks.length,
}
},
}
},
})
return obj
}