how do i dynamically create a multidimensional javascript array

I'm trying to dynamically build a javascript array where _tags is a globally defined array and then send it to php via ajax request. Basically I need the uid as a key and x,y as a sub array. in php it would look something like

$arr[$uid] = array('x'=>$x,'y'=>$y); 

but im having trouble figuring out an array like this in javascript, heres what i have

function add_tag_queue(uid,x,y){

    var arr = new Array(3);
    arr[0] = uid;
    arr[1] = x;
    arr[2] = y;

    _tags.push(arr);
}

Answers


This works ok as long as their is only one entry being added to the array, I'm adding multiple values, in other words the function will run a few times and then i want to send that entire array, but this seems to just be adding everything with a comma delimeter.

Im not sure what youre saying exactly here. The second example i previously gave assumes there is a single x,y pair for each uid but places no limits on how many uids are in _tags. Thats why var _tags = {}; is ourside of the function - so its a global variable.

The following modifications would allow you to have multiple x,y pairs for each uid:

function add_tag_queue(uid,x,y){

   /* 
    * detect if _tags[uid] already exists with one or more values 
    * we assume if its not undefined then the value is an array... 
    * this is similar to doing isset($_tags[$uid]) in php
    */
   if(typeof _tags[uid] == 'undefined'){
     /* 
      * use an array literal by enclosing the value in [], 
      * this makes _tags[uid] and array with eah element of 
      * that array being a hash with an x and y value
      */
     _tags[uid] = [{'x':x,'y':y}]; 
   } else {
     // if _tags[uid] is already defined push the new x,y onto it
     _tags[uid].push({'x':x, 'y':y});
   }
}

This should work:

function add_tag_queue(uid,x,y){

    _tags.push([uid, x,y]);
}

if you want the uid as the key then you need to use an object/hash not an array

var _tags = {}; // tags is an object
function add_tag_queue(uid,x,y){

        _tags[uid] = {'x':x,'y':y};
    }

Need Your Help

Make text box respond to treeview selection

c# treeview

In this project there are multiple reports being generated. Each report can have unlimited subreports, making this a completely recursive solution. I need to make a C# viewer to show these report...

Hide Primefaces datatable 'No Records Found' while loading the table content

jsf datatable primefaces

In my application im loading my data table with default values which placed in first page(After Logged in).while loading data,data table prompts 'No Record Found' which is confusing to the user.how...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.