How to create an array of objects?

Solved
Yurika
Tourist
4 0 1

I want to create an array of objects on the checkout page like this:

  items = [
    {
      productId: "P001",
      size:      "L",
      variantId: "P001_SIZEL_RED",
      url:       "http://example.com/products/P001",
      imageUrl: "http://images.example.com/products/P001/red/image1xl.jpg",
      color:     "Red",
      unitPrice: 5100,
      quantity:  1,
      gender: "W"
    }
    ...// Create an object for each of the items that were purchased in the order
  ]

I can get the individual values by looping through `checkout.line_items` but I can't figure out how to store them as objects and push them into an array. Can you please help me?

0 Likes
David_Weru
Trailblazer
129 9 21

This is an accepted solution.

 

Hello @Yurika 

You'll have to inline it if you want to give js access to it, or use cartjs. Below is psuedo code on how you'd pass data to js.

 

Items={}; //javascript

{%liquid line_item loop%} //liquid

Items.push( {{current_line_item}} );//javascript

{%liquid line_item_loop%} //liquid

 

 

 

 

Yurika
Tourist
4 0 1

Thanks @David_Weru I got it to work like so:

var items = [];

{% for line_item in checkout.line_items %}

{% for option in line_item.options_with_values %}
{% if option.name == 'Size' %}
{% assign size =  option.value %}
{% endif %}
{% if option.name == 'Color' %}
{% assign color = option.value %}
{% endif %}
{%endfor%}

var item = {}
item.productId = "{{line_item.product_id}}"
item.size = "{{size}}"
item.variantId = "{{line_item.variant_id}}"
item.url = "{{line_item.url}}"
item.imageUrl = "{{line_item.image}}"
item.color = "{{color}}"
item.unitPrice = {{line_item.original_price}}
item.quantity =  {{line_item.quantity}}
item.currency = "JPY"
item.gender = "NA"
items.push(item);

 {% endfor %}
David_Weru
Trailblazer
129 9 21

That's great @Yurika

Just note that in using this method, you must refresh the page to update your javascript.  To use ajax, and update without refreshing, I'd suggest using cartjs.  

Also, thank you for selecting my solution.