espresso_coffee
espresso_coffee

Reputation: 6110

How to create object or array that will start from specific number?

I would like to create object or array that will start loop from #32. I have tried something like this:

var test = [{'recID':"32",'optionalCol':"first",'recID':"33",'optionalCol':"last",'recID':"34",'optionalCol':"age"}];

This did not work for me, I tried to do the loop like this:

for(var i=32; i < test.lenght; i++) {
    console.log(test[i].recID);
}

I'm wondering if this is possible and how my object/array has to be structured in order to be able to start my loop from 32? If anyone can help please let me know.

Upvotes: 1

Views: 46

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386660

You could use an Object with the numbers as keys and with objects inside, which reflects the values in your given example.

var test = {
    32: {
        'recID': "32",
        'optionalCol': "first"
    },
    33: {
        'recID': "33",
        'optionalCol': "last"
    },
    34: {
        'recID': "34",
        'optionalCol': "age"
    }
};

This structure allows to access a property with

test[33].optionalCol

Iterate with

Object.keys(test).forEach(function (key, i, keys) {
    // test[k] ...
});

Count of properties of the object

Object.keys(test).length // 3

Upvotes: 1

Martin Gottweis
Martin Gottweis

Reputation: 2739

What you want to do is to use associative array like this:

var test = {
    32: "first",
    33: "last",
    34: "age"
}

You can iterate the object like this:

for (t in test) {
    console.log(test[t])
}

Or just access an item quickly like this:

console.log(test[33])

Check out the jsfiddle: https://jsfiddle.net/xo0vuejt/

Upvotes: 2

Related Questions