Currently in my Javascript code, I am setting up an array where the product id serves as the key. However, due to the numeric nature of the key, the array ends up filling gaps with null values.
For instance, if I only have two products with ids 5 and 7, the setup might look like this:
var arr = []
arr[5] = 'my first product';
arr[7] = 'my second product';
When I pass this array to a PHP script and print it out, I encounter the issue of getting unnecessary null entries like below;
Array (
[0] = null
[1] = null
[2] = null
[3] = null
[4] = null
[5] = My first product
[6] = null
[7] = My second product
)
My product ID numbers are rather lengthy (6 digits), causing excessive iterations when looping over the array, even for just a few products.
I am seeking advice on how to structure the array to avoid these null values. Considering making the key a string instead crossed my mind, but implementing this dynamically is posing a challenge.
var arr = [];
for(var i=0; i<products.length; i++)
{
array[products[i].id] = products[i].name;
}
Any suggestions or solutions would be greatly appreciated!