Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery creating two dimensional array

Edit: It appears I was a bit confused on what I was trying to accomplish. For those that took the time to explain this, thank you.

I'm trying to create a two dimensional array in Jquery/Javascript. I've done a decent amount of searching, testing and more searching but i'm unable to find a solution that really makes sense to me. (it's been a very long week already....)

Below is the desired format of the array.

{"product":[{"attribute":"value","attribute":"value"}]}
like image 266
Stephen S. Avatar asked Aug 03 '11 20:08

Stephen S.


People also ask

How to make 2 dimensional array in JavaScript?

Javascript only has 1-dimensional arrays, but you can build arrays of arrays, as others pointed out. The number of columns is not really important, because it is not required to specify the size of an array before using it. Then you can just call: var arr = Create2DArray(100); arr[50][2] = 5; arr[70][5] = 7454; // ...


2 Answers

You can't create a two dimensional array in Javascript, arrays can only have one dimension. Jagged arrays, i.e. arrays of arrays, are used instead of two dimensional arrays.

Example:

var a = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

The desired format that you show is neither a two dimensional array nor a jagged array, instead it's an object containing a property that is an array of objects. However, the object in the array has two properties with the same name, so I assume, you meant that as having two objects in the array:

var o = {
  product: [
    { attribute: "value" },
    { attribute: "value" }
  ]
};

You can create an object like that using a literal object like above, or you can create it by adding properties and array items afterwards:

var o = {};
o.product = [];
o.product.push({ attribute: "value" });
o.product.push({ attribute: "value" });
like image 144
Guffa Avatar answered Oct 17 '22 02:10

Guffa


That's not a 2D array, but rather an object. Also, your product array contains only one object. I think you need something like this:

var obj = {};
obj.product = [];
for(var i=0; i < someObj.length; i++) {
   obj.product.push[{"attribute": someObj[i]}]
}

This will produce an array inside the product property:

{"product":[{"attribute":"value"}, {"attribute":"value"}]}
like image 29
Mrchief Avatar answered Oct 17 '22 02:10

Mrchief