更新GTM数据层时,如何删除旧数据?

时间:2018-02-15 12:51:27

标签: javascript google-tag-manager

我需要在进行ajax调用后更新数据层。

我们在产品类别页面上,初始数据层代码如下所示:

var dataLayer = [({
    "categoryProducts": [{
        "id": "3",
        "name": "Golden Bridge Bicycle Tour",
        "sku": "bicycle-tour",
        "gender": false,
        "category": "All Tours",
        "position": 0
    }, {
        "id": "17",
        "name": "Golden Bridge Walking Tour",
        "sku": "walking-tour",
        "gender": false,
        "category": "All Tours",
        "position": 1
    }, {
        "id": "27",
        "name": "Golden Bridge Private Bicycle Tour",
        "sku": "private-bicycle-tour",
        "gender": false,
        "category": "All Tours",
        "position": 2
    }],
    "categorySize": 3,
    "customerLoggedIn": 0,
    "customerId": 0,
    "customerGroupId": "1",
    "customerGroupCode": "GENERAL",
    "categoryId": "3",
    "categoryName": "All Tours",
    "pageType": "catalog\/category\/view"
})];
dataLayer.push({
    "categoryName": "All Tours Filtered",
    'ecommerce': {
        "impressions": [{
            "id": "3",
            "name": "Golden Bridge Bicycle Tour",
            "sku": "bicycle-tour",
            "gender": false,
            "category": "All Tours",
            "position": 0
        }, {
            "id": "17",
            "name": "Golden Bridge Walking Tour",
            "sku": "walking-tour",
            "gender": false,
            "category": "All Tours",
            "position": 1
        }, {
            "id": "27",
            "name": "Golden Bridge Private Bicycle Tour",
            "sku": "private-bicycle-tour",
            "gender": false,
            "category": "All Tours",
            "position": 2
        }]
    }
});

假设我们点击过滤器并使用ajax调用现在只显示了2个产品,所以我想使用此代码在数据层中显示:

    dataLayer.push({
    "categoryName": "All Tours Filtered 1",
    "categorySize": 2,
    "categoryProducts": [{
        "id": "33",
        "name": "Golden Bridge Segway Tour",
        "sku": "segway-tour",
        "gender": false,
        "category": "All Tours",
        "position": 0
    }, {
        "id": "17",
        "name": "Golden Bridge Walking Tour",
        "sku": "walking-tour",
        "gender": false,
        "category": "All Tours",
        "position": 1
    }],
    'ecommerce': {
        "impressions": [{
            "id": "33",
            "name": "Golden Bridge Segway Tour",
            "sku": "segway-tour",
            "gender": false,
            "category": "All Tours",
            "position": 0
        }, {
            "id": "17",
            "name": "Golden Bridge Walking Tour",
            "sku": "walking-tour",
            "gender": false,
            "category": "All Tours",
            "position": 1
        }]
    }
});

但是,不是更新产品数组,而是添加它们。现在数据层有5个产品。

1 个答案:

答案 0 :(得分:0)

使用dataLayer.push(obj)obj添加到现有dataLayer而不重置它。

要重置dataLayer,请使用以下命令:

window['google_tag_manager']['GTM-XXXXXX'].dataLayer.reset();