Shiro Shiro - 19 days ago 9
Javascript Question

Javascript Array key as variable

I im building and array where my array key is from a variable like this:

var product_id = $('#product_id').val(); //22
var art = $('#article_id').val(); //229
var stk = $('#stk').val(); //20
var elements = [];
elements [art] = stk;
console.log(elements);


This is the result

Array[229]
228:"20"
length:229
__proto__:Array[0]


console.log

As you see the result, it actually created 229 array key,

When I make a AJAX POST with that variable. It post all 229 array item to it.

option[]:
option[]:
option[]:
option[]:
option[]:
option[]:
option[]:
option[]:
option[]:
option[]:
option[]:
option[]:20


post object

It is possible I just want to post 1 key and value.

elements[229] = 20;


Not all the unused. Thanks!

Below is my ajax call

$.ajax({
url: 'product/getprice',
type: 'post',
data: { product_id: product_id, option: element },
dataType: 'text',
beforeSend: function() {
},
complete: function() {

},
success: function(json) {

json = JSON.parse(json);

},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});

Answer

The array you're creating is a sparse array (an array with lots of missing entries). It sounds like whatever it is that you're using to serialize the array doesn't handle sparse arrays the way you want it to, instead acting as though the array weren't sparse.

So that gives you two options at least:

  1. Change the serialization code. Since you haven't shown it, we can't help you there.

    or

  2. Use an object instead of an array:

    var elements = {}; // Note {}, not []
    

    None of the other code you've shown has to change, but it's possible your serialization code may need to change if you do this.