var dataJson = JSON.stringify({ "11501": { "Name": "11501", "RecipeName": "N", "Time": 10, "Ingredient1ID": 1, "Ingredient1Quantity": 2, }, "11502": { "Name": "11502", "RecipeName": "N", "Time": 10, "Ingredient1ID": 2, "Ingredient1Quantity": 2, }, }); var jsonobject = JSON.parse(dataJson); element = {}; function addElement(e, t) { element[jsonobject[e]['Ingredient1ID']] += jsonobject[e]['Ingredient1Quantity']; console.log(element); }
<button type="button" class="btn bg-purple btn-flat margin" onclick="addElement(11501,10);"> <i class="fa fa-plus"></i> Add to queue </button> <button type="button" class="btn bg-purple btn-flat margin" onclick="addElement(11502,10);"> <i class="fa fa-plus"></i> Add to queue item2 </button>
addElement is a onClick function its supposed to sum quantity of element[key] on each click, if the key exists it should add the value such as += does.
Currently it outputs Object {11001: NaN} since it has no basic value though. I can not provide basic value for the key since they are dynamic numbers example:
First click
Object {ID: Qty}
Object {11501: 2}
Object {11501: 2+2}
Is there an option to accomplish this sum functionality? It could be also an array if its easier.
You should use parseInt()
on your quantity and then add. This will work. Currently, you are trying to add the values which are not integers. Thanks
Have a look at this example. I hope I understood what you're trying to do.
var queue = {}; var jsonobject = { "11501": { "Ingredient1ID": 1, "Ingredient1Quantity": 2, }, "11502": { "Ingredient1ID": 2, "Ingredient1Quantity": 2, } }; function addElement(e, t) { var elementId = jsonobject[e]['Ingredient1ID']; var elementQuantity = jsonobject[e]['Ingredient1Quantity']; if (!(elementId in queue)) { queue[elementId] = elementQuantity; } else { queue[elementId] += elementQuantity; } console.log(queue); }
<button type="button" onclick="addElement(11501,10);">Add item1 to queue</button> <button type="button" onclick="addElement(11502,10);">Add item2 to queue</button>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.