var myCars=[{ "name": "Axio", "priceLakh":22.5 }, { "name": "Axio0", "priceLakh":22.5 }, { "name": "Axio00", "priceLakh":22.5 }, { "name": "Axio000", "priceLakh":22.5 },]
Asked
Active
Viewed 132 times
-2
-
1Does this answer your question? [How to sum value of two json object key?](https://stackoverflow.com/questions/44436041/how-to-sum-value-of-two-json-object-key) – ORHAN ERDAY May 28 '22 at 08:44
3 Answers
1
you can use reduce
var myCars=[{ "name": "Axio", "priceLakh":22.5 }, { "name": "Axio0", "priceLakh":22.5 }, { "name": "Axio00", "priceLakh":22.5 }, { "name": "Axio000", "priceLakh":22.5 },]
const sum = myCars.reduce((res, {priceLakh}) => res + priceLakh, 0 )
console.log(sum)

R4ncid
- 6,944
- 1
- 4
- 18
0
You can use forEach
loop to calculate the sum.
var myCars=[{ "name": "Axio", "priceLakh":22.5 }, { "name": "Axio0", "priceLakh":22.5 }, { "name": "Axio00", "priceLakh":22.5 }, { "name": "Axio000", "priceLakh":22.5 }],sum=0;
myCars.forEach(element => {sum=sum+element.priceLakh;});
console.log("₹"+sum+" Lakhs")

Sumit Sharma
- 1,192
- 1
- 4
- 18
-
-
-
It really is not. You're defining a variable for it and then manipulate it. It's 2 lines at best. One line means a single expression. – Robo Robok May 28 '22 at 19:59
0
You can use something like this. The reduce operator and destructuring feature
var myCars = [
{ name: "Axio", priceLakh: 22.5 },
{ name: "Axio0", priceLakh: 22.5 },
{ name: "Axio00", priceLakh: 22.5 },
{ name: "Axio000", priceLakh: 22.5 },
];
var answer = myCars.reduce((partialSum, {priceLakh}) => partialSum + priceLakh, 0);
console.log(answer);

VLAZ
- 26,331
- 9
- 49
- 67

InfernoCheese
- 94
- 5