I currently have this
<option ng-id="1186384773090640435" value="1186384956868264500">Product Name</option>
I need to take both id and value and insert it into this below:
moltin.Cart.Insert($scope.productId, qty, { "1186384773090640435" : { "1186384956868264500" : 1} }, function (cart) {
How do I do this?
I am currently doing something like this at the moment but it doesnt work:
modi = $(this).attr('ng-id');
vari = $(this).attr('value');
moltin.Cart.Insert($scope.productId, qty, { modi : { vari : 1} }, function (cart) {
I can assume its because the values are not strings or objects. Not quite sure.
You cannot use variable values as object attribute names when creating object literals (except if you are writing ES20015). You will need something like :
modi = $(this).attr('ng-id');
vari = $(this).attr('value');
((insert = {})[modi] = {})[vari] = 1
moltin.Cart.Insert ($scope.productId, qty, insert, function ( ...
Explanation:
In the third line we first set a variable named insert
to an empty object (insert = {})
. To that object we add an attribute whose name is the value of variable modi
and whose value is an empty object : ( ...[modi] = {})
. That empty object is in turn given an attribute whose name is the value of vari
and whose value is 1. The whole expression returns the value 1 which explains why we need to set a variable name to reference the first created object.
Javascript so so accomodating ;-)
or (in three lines an only one var) :
let insert = {};
(insert[$(this).attr('ng-id')] = {})[$(this).attr('value')] = 1
moltin.Cart.Insert ($scope.productId, qty, insert, function ( ...
In ES2015 (ES6) this you can code this directly as :
moltin.Cart.Insert ($scope.productId, qty, {[modi]: {[vari]: 1}}, function ( ...