2

Is there an efficient way to loop through the keys in a JSON array that start with the key name 'option' and either loop through them all or set a max?

I'm currently doing this following:

$.each(shopifyProductJSON.variants, function(index, variant) {
    variantOptions = new Array();
    variantOptions.push(variant.option1);
    variantOptions.push(variant.option2);
    variantOptions.push(variant.option3);
});

Which is fine but want it to be more dynamic in case more options are added in the future.

An example of part of the JSON array for each variant:

inventory_management: null
inventory_policy: "deny"
inventory_quantity: 0
old_inventory_quantity: 0
option1: "Bronze"
option2: "Satin Gold"
option3: "600mm"
position: 1
price: "550.00"

I thought this would've worked...

variantOptions = new Array();
for (i = 1; i < 4; i++) {
    var key = 'option' + i;
    variantOptions.push(key);
}
1
  • Agreed. In the API for the restAPI they return them as those option1, option2 keys... which is stupid. In the JS API they return them as an array but for rate limits I'm dumping the JSON using the restAPI so I'm stuck with it. help.shopify.com/en/api/reference/products/product#show Commented Nov 30, 2018 at 10:54

1 Answer 1

1

To solve your immediate issue you need to access the objects properties in the loop, not push the string in to the array:

let variantOptions = [];
for (i = 1; i < 4; i++) {
  var key = 'option' + i;
  if (data.hasOwnProperty(key)) {
    variantOptions.push(data[key]);
  }
}

That being said, if the options are going to be of a dynamic length it makes far more sense to return them as an array instead of individual numbered properties, assuming you have control over the response format.

You could change the response to this:

{
  inventory_management: null
  inventory_policy: "deny"
  inventory_quantity: 0
  old_inventory_quantity: 0
  options: ['Bronze', 'Satin Gold', '600mm'],
  position: 1
  price: "550.00"
}

Then the JS to access the options becomes a simple property accessor:

let variantOptions = data.options;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.