jim February 2016

Javascript syntax inside array

I have to push an array in jquery. I can't get how to properly format all javascript syntax. Can you share the best solution on this.

Result should be like this.

<script type="text/javascript">
rrApiOnReady.push(function() {
    try {
        rrApi.order({
            transaction: <transaction_id>,
            items: [
                { id: <product_id>, qnt: <quantity>,  price: <price>},
                { id: <product_id>, qnt: <quantity>,  price: <price> }
            ]
        });
    } catch(e) {}
})
</script>

I determine variable for 'order.cart.items' and then trying to list an array with 'items[i].product.id' like in tutorials:

var items = order.cart.items;
for (var i in items) { ... }

But it doesn't work for me to put it in the specific formatting above. It returns an error Uncaught SyntaxError: Unexpected token for.

rrApiOnReady.push(function() {
            try {
            rrApi.order({
            transaction: page.orderNumber,
            items: [
              for (var j in items) {
              { id: items[j].product.id, qnt: items[j].quantity,  price: items[j].product.price },
              }
                        ]
                    });
                    } catch(e) {}
                });

Can you please guide me how to properly format an array in such a case? Thanks in advance!

Answers


meagar February 2016

You can't use a for loop inside a larger structure. JavaScript's for loops to are not expressions which can be evaluated to a value. They are rooted in imperative programming, not functional programming.

Instead, you should use map, which does return a new collection based on your input collection:

rrApi.order({
  transaction: page.orderNumber,
  items: items.map(function (item) {
    return { id: item.product.id, qnt: item.quantity, price: item.product.price }  
  })
})

Post Status

Asked in February 2016
Viewed 2,664 times
Voted 10
Answered 1 times

Search




Leave an answer