0

seems I cant find an answer to this anywhere

I have an array

array=["id1" : "somedata", "id2" : "somedata2",....]

so I can index it with a special db id but what if I want to iterate (integer) through this array from a start position ?

for(i=5;i<10;i++)
   array[i]... <= complains that index dont exist of course 
Satpal
  • 132,252
  • 13
  • 159
  • 168
Phil
  • 708
  • 1
  • 11
  • 22

5 Answers5

1

That doesn't seem to be an valid array.

Either do:

array=[{"id1" : "somedata"}, {"id2" : "somedata2"},....]

Or:

object={"id1" : "somedata", "id2" : "somedata2",....}

Anyway, to iterate over the array:

for(i=5;i<10;i++) { // or i = 5; i < 10 && i < array.length; i++
    if(array[i]) { // check if the index exists, also you could use array[i] !== undefined
        ....
    }
}
Sebastian Nette
  • 7,364
  • 2
  • 17
  • 17
0

An "associative array" in Javascript is basically an Object. So, you can use Object.keys to retrieve the keys & grab the related index:

var keys = Object.keys(arr);
for(i=5; i<10; i++) {
    var keyName = keys[i]; // "id1", "id2", etc.
    console.log(arr[keyName]); // "somedata"
}

jsFiddle

CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
0

First of all, its not an array[] but an object {}, now what you can do is take each of these values, and store them into an index, or create your own array of objects, I'm not sure exactly what your next requirements are

array={"id1" : "somedata", "id2" : "somedata2"};
$.each(array, function( index, value ) {
  console.log( index + ": " + value );
});
Dejan Biljecki
  • 595
  • 1
  • 5
  • 26
0

Try this,

split the values of array.

function array_values(input) {      

  var tmp_arr = [],
    key = '';

  if (input && typeof input === 'object' && input.change_key_case) { // Duck-type check for our own array()-created PHPJS_Array
    return input.values();
  }

  for (key in input) {
    tmp_arr[tmp_arr.length] = input[key];
  }

  return tmp_arr;
}

usage :

var new_array = array_values(your_array);

Now your new_array has values with index 0,1,2... you can do for loop now..

ramamoorthy_villi
  • 1,939
  • 1
  • 17
  • 40
0

Assuming your array is define like this:

array={"id1" : "somedata","id2" : "somedata2"};

This will loop through the array with the index you need, example:

for (var k in array){
    if (array.hasOwnProperty(k)) {
         alert("Key is " + k + ", value is" + array[k]);
    }
}
Ahs N
  • 8,233
  • 1
  • 28
  • 33