Here is My code :
function addtocart(id,price) {
var qty = $("#txt_qty" + id).val();
var qty1 = new Array();
if (qty == '' || qty == 0) {
alert('Please Enter Quantity');
$("#txt_qty" + id).focus();
return false;
}
if (qty != '' && type != '') {
proid.push(id);
var text = 'qty'+id+'='+qty;
var keyValuePair = text.replace(/ /g,'').split('=');
qty1.push([keyValuePair[0]] = [keyValuePair[1]]);
}
I need to store key in qty1
array,I have already value called qty
How can i dynamically store key in qty1
array
I am trying above attempt but not succeeded
Can anybody help me
Associative array (name index) are treated as object in javascript/jquery. So you can use like this
var qty1= {"key1":"value1", "key2":"value2", "key3":"value3"};
var test = qty1.key1; // "value1" will be returned
Or you can use array like this but it will be converted in object as above
var qty1= [];
qty1["key1"] = "value1";
qty1["key2"] = "value2";
qty1["key3"] = "value3";
var test = qty1[0]; // qty1[0] will return undefined
var test2 = qty1.key1; // "value1" will be returned
If you got already data value for keyvaluepair[0]
and keyvaluepair[1]
, then try use this :
var myObj = {}; // declare obj container
myObj[keyvaluepair[0]] = keyvaluepair[1]; // set key and value based on your variable
qty1.push(obj); // finally push obj into your qty1(array) variable
This is just an alternative, you can try use the solution provided by @Disha V.
Try this : You need to set value against specific key, see below code. Also define new map like belwo
var qty1 = new Object();//create new map and not array
qty1[keyValuePair[0]] = keyValuePair[1];
to read value again from map use below code
var value = qty1[keyValuePair[0]];