如何在Json对象中动态推送Json数组

时间:2015-02-25 13:06:13

标签: javascript jquery json object

$('#form1').submit(function(e) {
    e.preventDefault(); 
    dataLayer = [];
    dataLayer.push({
        'event': 'pre-addToCart',
        'ecommerce': {
            'currencyCode': 'EUR',
            'add': {
                'products': [] // I need to insert the products data here directly instead of pushing it 
            }
        }
    });

这是在创建对象后我正在进行的操作。我希望这可以直接在对象中完成。有什么想法吗?

var length = $(".booking-ticket-table tbody tr").length;
for (var i = 0; i <= length; i++) {
    var prod_sku = $(".booking-ticket-table  td.alpha")[i].textContent.trim().split(/\s/).join('');
    var prod_name = $(".booking-ticket-table  td.alpha")[i].textContent.trim();     //Prod name
    var prod_price = $(".booking-ticket-table td.omega")[i].textContent.trim().replace('£','');     //Prod Price
    var prod_qty = $(".booking-ticket-table  td:nth-of-type(2) input")[i].getAttribute("value");        //Prod Qty

    dataLayer[0].ecommerce.add.products.push({
        "id":"1232",
        "sku":prod_sku,
        "name": prod_name,
        "price": prod_price,
        "quantity": prod_qty 
    });
}
});

1 个答案:

答案 0 :(得分:0)

您可以尝试将第二个代码块封装到一个函数中。真的没什么区别,但更模块化了:

$('#form1').submit(function(e) {
e.preventDefault(); 
dataLayer = [];
dataLayer.push({
    'event': 'pre-addToCart',
    'ecommerce': {
        'currencyCode': 'EUR',
        'add': {
            'products': buildProducts() //returns the array
        }
    }
});

buildProducts看起来像:

function buildProducts(){
    var theProducts = [];
    var length = $(".booking-ticket-table tbody tr").length;
    for (var i = 0; i <= length; i++) {
        var prod_sku = $(".booking-ticket-table  td.alpha")[i].textContent.trim().split(/\s/).join('');
        var prod_name = $(".booking-ticket-table  td.alpha")[i].textContent.trim();
        var prod_price = $(".booking-ticket-table td.omega")[i].textContent.trim().replace('£','');
        var prod_qty = $(".booking-ticket-table  td:nth-of-type(2) input")[i].getAttribute("value");

        theProducts.push({
            "id":"1232",
            "sku":prod_sku,
            "name": prod_name,
            "price": prod_price,
            "quantity": prod_qty 
        });
    }

    return theProducts;
}