Assign shopify variable object to javascript as an object

I am attempting to extract product data into a javascript variable, so that I can work with the whole object in my javascript, however I can’t seem to figure out the correct syntax, I have tried the following:

{% assign upsellProduct1 = all_products['laundry-bag'] %} 
 

And different variations of it, but I can’t seem to get it to work. If I try to assign a specific property, it works, but otherwise it just gives me ProductDrop.

So these are the variants that I have tried:

const product = {'{{upsellProduct1}}'};  // doesnt work -> ProductDrop
  const product = '{{{upsellProduct1}}}';  // doesnt work -> ProductDrop
  const product = { ...{{upsellProduct1}} }; // doesnt work -> ProductDrop
  const product = '{{upsellProduct1.handle}}'; // specific property works

What is the correct way to assign the whole product to a javascript variable?

Hey! So this depends on what page you’re wanting to use the variable on.

If you’re just using this on a product page, then the product object is available and can be stored in a variable like this, and the JSON is accessible through the JSON liquid filter:

var myProductVariable = {{ product | json }};

If you need to get one particular product and use the variable anywhere in your code, you’d do this:

var myProductVariable = {{ all_products['my-product-handle'] | json }};

And of course, this Javascript can only be used in a js file ending in .liquid so that the liquid is rendered (a pretty obvious statement, but an easy one to accidentally forget!)