简体   繁体   中英

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 } ]

I don't see why not:

products_list.push({
        id: input[i].id.slice(0,6),
        price: input[i].price,
        quantity: input[i].quantity
});

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM