我有一些javascript数组,我无法控制格式或变量名称。我需要将它们中的6个组合成一个json数组。我有它非常接近,但似乎无法让它迭代变量列表以及数组元素的数量。
对我来说很明显,我不记得如何处理JS中的变量或迭代,以及我以前可以使用的一些帮助。
我需要解析其输出的软件会产生类似于以下内容的内容:
<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>
由于我需要传递数据的软件也需要以下内容(作为对象,我设法使用字符串完成它):
[
{
"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",
]
这就是我想出的:
<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;
它生成格式正确的数据,但缓冲区硬编码值指示的元素的6个相同副本
答案 0 :(得分:1)
有些事情:
function createItemObjects(items, ids, codes, qtys, prices, images) {
var check = items.length === ids.length && ids.length === codes.length &&
qtys.length === codes.length && prices.length === images.length;
if(!check) throw 'Arrays do not match';
var results = [];
for(var i = 0; i < items.length; ++i) {
results.push({
item_id: ids[i],
desc: codes[i],
amount: parseFloat(prices[i]),
name: items[i],
quantity: qtys[i],
image: images[i]
})
}
return results;
}
var data = generate(items, ids, codes, qtys, prices, itemImages);
var json_string = JSON.stringify(data);