Search code examples
javascriptgoogle-datalayer

How to slice an object while push method


I'm trying to slice input[i].id which looks like 1012410001 to 101241 (slice(0,6)). Is it possible to slice it with the push method or should it be done before?

function() {
    var input = {{dataLayer - purchase_products}};
    var products_list = [];
    for(i=0;i<input.length;i++){
        products_list.push({
            id: input[i].id,
            price: input[i].price,
            quantity: input[i].quantity
        });
    }
    return products_list;
}

dataLayer - purchase_products = [ { quantity: 1, coupon: [], name: 'Lancôme La vie est belle Eau de Parfum', id: '1012410001', price: 41.9, brand: 'Lancôme', category: 'Eau de Parfum', variant: null } ]

Solution

  • Sure, you can do that within the push.

    You can also do a map (Assuming you're using ES6):

    function() {
        var input = {{dataLayer - purchase_products}};
        var products_list = input.map((item) => {
            id: item.id.slice(0,6),
            price: item.price,
            quantity: item.quantity
        });
        return products_list;
    }