I have a handful of javascript arrays that I have no control over as far as format or variable names. I need to combine 6 of them into a json array. I have it pretty close but can't seem to get it to iterate through both the list of variables as well as the count of array elements.
It is apparent to me that I do not remember how to handle variables or iteration in JS as well as I used to and could really use some help.
The software whose output I needs to parse generates something similar to the following:
<script type="text/javascript">
var orderNum = 'OrderNum-485';
var orderSubTotal ='130.8';
var orderTotal ='130.8';
var numOfItems ='4';
var items =new Array('Item Name 1','Item Name 2','Item Name 3','Item Name 4');
var ids =new Array('item-id-1','item-id-2','item-id-3','item-id-4');
var codes =new Array('ITEM-CODE-1','ITEM-CODE-2','ITEM-CODE-3','ITEM-CODE-4');
var qtys =new Array('1','1','1','1');
var price =new Array('12.95','46.7','1.2','69.95');
var orderTax ='0';
var orderShipping ='0';
var appliedPromoIdList ='';
var coupon ='';
var storeId ='store_id';
var activeShipPromotionCount ='';
var itemImages =new Array('http://image_url','http://image_url','http://image_url','http://image_url');
</script>
Where as the software that I need to pass data too expects the following (as an object, I managed to get it done using strings):
[
{
"item_id":"item-id-1",
"desc":"ITEM-CODE-1",
"amount":"12.95",
"quantity":"1",
"name":"Item Name 1",
"image": "http://image_url",
{
"item_id":"item-id-2",
"desc":"ITEM-CODE-2",
"amount":"46.7",
"quantity":"1",
"name":"Item Name 2",
"image": "http://image_url",
]
This is what I came up with:
<script type="text/javascript">
var orderId = orderNum;
var createItemObjects = function() {
var keys = new Array ("item_id","desc","amount","quantity","name","image");
var yahooKeys = new Array ("ids","codes","price","qtys","items","itemImages");
var item,cartItems = [];
var c = numOfItems;
var k = yahooKeys.length;
var i = 0;
item = {};
for (; i < k; i++) {
var arrayName = yahooKeys[i].toString();
var buffer = eval('' + arrayName);
item[keys[i]] = buffer[0] //Ideally this should be the full range of 0-3 so that you can see each of the 4 items.
document.write("<br />Loop: "+i);
cartItems.push(item);
}
return cartItems;
It generates correctly formatted data but 6 identical copies of the element indicated by buffer's hard coded value