简体   繁体   中英

Javascript : Can't retrieve value from array

I have a code

alert(JSON.stringify((this.shop.get('selectedOrder')).get('orderLines')));

The Result look like this

[{"cart_weight":0,"total_weight":1,"quantity":1,"list_price":1,"discount":0,"ean13":false,"product_image_small":false,"name":"Watermelon1","pos_categ_id":[1,"Others"],"taxes_id":[],"id":2}]

When I run this code

alert((this.shop.get('selectedOrder')).get('orderLines').total_weight);

The result become

undefined

Any export can help ?

I suspect is the double bracket causing the issue [{ }], but I am new to javascript. Not able to solve the issue.

Thank you.

Try alert((this.shop.get('selectedOrder').get('orderLines')[0].total_weight);

As you suspect, your result is not an object (in javascript terminology, any data between {} ) but an array ( [] ) containing one object. So you have to access the first element of your array before accessing the attribute.

Your selected order has multiple lines. You need to choose which line to get the total_weight from. In this case, there is only one line - so you can reference this using [0] . IE:

alert((this.shop.get('selectedOrder')).get('orderLines')[0].total_weight);

If instead, for example, you needed to calculate the weight of the entire order, you could iterate over all the order lines, and calculate the sum.

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