Javascript - Create Iterable Abstraction Layer

Viewed 204

Assuming I have an object like this:

var result = {
    items: [
        'item1', 'item2', 'item3'
    ]
}

I'm looking for a way create an object that would abstract my result object and yet would remain compatible to it:

function wrapper(result) {
    this.items = ???
}

In order to able able to do this

var p = new wrapper(result);

for(var x = 0; x < p.items.length; x++) {
    console.log(p[x]) // = item1, item2, item3
}

This can be easily accomplished in PHP using ArrayIterator. I was wondering if it can be done in JS, specifically in NodeJS.

Just to clarify:

Imagine the original object is a result from a db query. However, the formatting of that result object cannot be fed into the consumer as-is and needs to be adapted. In this case I did not dwell on the adaptation but for the sake of the example assume each value needs to be uppercased.

Additionally, the original list is very large. I could obviously iterate, copy all values and uppercase them, but in most cases it will not be required for all values, therefore it would be inefficient to do this for all items every time. The idea of the wrapper is to act as a proxy that I would be able to iterate. The wrapper will in turn retrieve the result from the original object, and modify it on the fly.

2 Answers
Related