Here is my object:
var obj = {
"idtransact1": {
"amount": 3000,
},
"idtransact2": {
"amount": 3000,
}
}
I am trying to get the sum of all amount. I tried to adapt this example but since it is not the same data structure then i am a bit lost.
var array = [{
"adults": 2,
"children": 3
}, {
"adults": 2,
"children": 1
}];
var val = array.reduce(function(previousValue, currentValue) {
return {
adults: previousValue.adults + currentValue.adults,
children: previousValue.children + currentValue.children
}
});
console.log(val);
Any help would be appreciated.
You can use Object.values()
and .reduce()
to get the sum:
const data = { "idtransact1": { "amount": 3000 }, "idtransact2": { "amount": 3000 } }; const result = Object.values(data).reduce((r, { amount }) => r + amount, 0); console.log(result);
Using forEach
loop
var obj = { "idtransact1": { "amount": 3000, }, "idtransact2": { "amount": 3000, } } var sum=0; Object.values(obj).forEach((x)=>sum+=x.amount) console.log(sum)
A for in loop is your friend when it comes to looking for values in an object.
var obj = {
"idtransact1": {"amount": 3000},
"idtransact2": {"amount": 3000}};
var sumAmount = 0;
for(var char in obj){
sumAmount += obj[char].amount;
}
console.log(sumAmount);
For your second example, the for in loop works the same way with the array of objects.
var array = [
{"adults": 2,"children": 3},
{"adults": 2,"children": 1}];
var sumAdults = 0;
var sumChildren = 0;
for(var char in array){
sumAdults += array[char].adults;
sumChildren += array[char].children;
}
console.log(sumAdults + " " + sumChildren);
Less to remember if you can look for data in objects and data in an array of objects the same way. Enjoy
Array [
Object {
"product": Object {
"cat_id": "20",
"cat_name": "Pizza",
"detail": "Pizza sauce, Green pepper & mozarella cheese",
"discount_price": "",
"has_extra": "0",
"has_variation": "1",
"id": "46",
"image": "chicken-tikka-piza-recipe-main-photo.jpg",
"name": "Chicken Fajita",
"prep_time": "30",
"price": "310",
"status": "1",
"time_stamp": "2021-01-02 19:43:41",
"ven_id": "6",
},
"quantity": 1,
},
Object {
"product": Object {
"cat_id": "20",
"cat_name": "Pizza",
"detail": "Pizza Sauce, Tomato Green Paper, Olives Mashrooms And Chipotle Sauce with extra Creamy mayoneese",
"discount_price": "",
"has_extra": "0",
"has_variation": "0",
"id": "45",
"image": "chicken-tikka-piza-recipe-main-photo.jpg",
"name": "Chicken Tikka",
"prep_time": "15",
"price": "310",
"status": "1",
"time_stamp": "2021-01-02 19:41:56",
"ven_id": "6",
},
"quantity": 3,
},
]
How to calculate its total price where quantity is not the same also I want to calculate total price
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.