1

I need to produce an array formatted as :

products : 
[
    {
        "product_id": 32,
        "quantity": 2
    },
    {
        "product_id": 33,
        "quantity": 2,
        "product_options": 
        [
            {
                "id": 87,
                "value": 10
            }
        ]
    }
]

I can do the product_id & quantity ok using :

productID = 32;
prodQuantity = 2;
var row2 = {};
row2.product_id = productID;
row2.quantity = prodQuantity;
product.push(row2);

productID = 33;
prodQuantity = 2;
var row2 = {};
row2.product_id = productID;
row2.quantity = prodQuantity;
product.push(row2);

How do I add the element product_options with the id & value.

I have tried variations of:

var row3 = {};
row3.id = 87;
row3.value = 10;    
cartArray['product_options'].push(row3);

I managed it using:

var prodQuantity = app.getValue('popupDropdown').value;
var cartArray = [];
var optionID = app.getValue('popupDropdown4').value;
var row2 = {};
var row3 = {};
var row4 = {};
var tempArray = [];
row2.product_id = productID;
row2.quantity = prodQuantity;
cartArray.push(row2);
row3.id = optionID;
row3.value = Rule4Value;
tempArray.push(row3);
row4.product_options = tempArray;
cartArray.push(row4);

But I see the answer below is much simpler.

1
  • No mention that the OP is using jQuery. Commented Apr 15, 2014 at 23:24

1 Answer 1

5

You can set the product_options of row2 like this:

row2.product_options = [
    {
        id: 87,
        value: 10
    }
];

To explain:

product_options is a key in row2. It's value is an array with a single element that is an object with the keys id and value.

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.