2

I've got a jQuery $.ajax() post and need to add an object (is it an object? string?) to the request for every item in an array. I'm lost as to the best method for doing this. I imagine it'd be best first to separate out the items from the data attribute as a variable so it's calculated before the request... but I'm not sure how to build each element. So here are some made up stuff to illustrate my point.

var items   = for (var i = 0; i < $orderItems.length; i++){
                  'item': {
                      'photo': $orderItems[0].photo,
                      'option': $orderItems[0].option,
                      'cost': $orderItems[0].cost
                  }
              },
    request = $.ajax ({
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        'firstName': $firstNameVal,
                        'lastName': $lastNameVal,
                        'email': $emailVal,
                        'phone': $numberVal,
                        'address': {
                            'street': $streetVal,
                            'city': $cityVal,
                            'state': $stateVal,
                            'zip': $zipVal
                        },
                        'price': $orderTotal,
                        'items': items
                    }
                });

1 Answer 1

2

You may use jQuery.map function to get items array:

var items = $.map($orderItems, function (item) {
     return {
          photo: item.photo,
          option: item.option,
          cost: item.cost
     };
});
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.