user3578905
user3578905

Reputation: 5

Javascript arrays storing values

There might be a very simple solution my problem but just not being able to find one so please help me to get to my solution in the simplest way...

The issue here is that I have data being displayed in a tabular form. Each row has 5 columns and in one of the columns it shows multiple values and so that's why I need to refer to a value by something like this row[1]['value1'], row[1]['value2'] & then row[2]['value1'], row[2]['value2'].

I declare the array

var parray = [[],[]];

I want to store the values in a loop something like this

for(counter = 0; counter < 10; counter ++){
     parray[counter]['id'] += 1;
     parray[counter]['isavailable'] += 0;
}

Later I want to loop through this and get the results:

for (var idx = 0; idx < parray.length; idx++) {
    var pt = {};
    pt.id = parray[schctr][idx].id;
    pt.isavailable = parray[schctr][idx].isavailable;
}

Obviously iit's not working because Counter is a numeric key and 'id' is a string key ..my question how do I achieve this ??

Thanks for all the answers in advance.

Upvotes: 0

Views: 65

Answers (2)

jshanley
jshanley

Reputation: 9128

What you want inside your array is just a plain object:

// just a regular array
var parray = [];

for(var counter = 0; counter < 10; counter++){
  // create an object to store the values
  var obj = {};
  obj.id = counter;
  obj.isavailable = 0;
  // add the object to the array
  parray.push(obj);
}

later:

for (var idx = 0; idx < parray.length; idx++) {
  var pt = parray[idx];
  // do something with pt
}

Upvotes: 1

Joseph
Joseph

Reputation: 119827

JS has no concept of "associative arrays". You have arrays and objects (map). Arrays are objects though, and you can put keys, but it's not advisable.

You can start off with a blank array

var parray = [];

And "push" objects into it

for(counter = 0; counter < 10; counter++){
  parray.push({
    id : 1,
    isAvailable : 0
  });
}

Then you can read from them

for (var idx = 0; idx < parray.length; idx++) {

  // Store the current item in a variable
  var pt = parray[idx];
  console.log(pt);

  // read just the id
  console.log(parray[idx].id);
}

Like I did here

Upvotes: 3

Related Questions