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"}]}
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; // ...
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" });
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"}]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With