1

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.

5
  • It should be test.length not test.lenght, not sure if that was just a typo. Commented Oct 5, 2016 at 14:48
  • is 32 a index? or is it related to the recID? like you need to start iterating where recID = 32? Commented Oct 5, 2016 at 14:50
  • Also, your test parameter is not array, it is an object. So you can't reach its elements by indexing (that's why test[32] doesn't work) Commented Oct 5, 2016 at 14:50
  • I should start my loop from 32 so my recID should be an index. Commented Oct 5, 2016 at 14:53
  • your properties get overwritten. Commented Oct 5, 2016 at 14:54

2 Answers 2

2

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/

Sign up to request clarification or add additional context in comments.

2 Comments

@MartinGotteweis How I can check the length of test variable? Usually I was doing this with test.length but I'm not sure that will work in this case.
.length is for arrays only. You can use Object.keys(test).length. The Object.keys() will take the object and return the array of the object's keys.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.