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 44 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
- 4,130
- 1
- 3
- 13
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,069
- 3
- 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
- 22,934
- 9
- 44
- 60
InfernoCheese
- 34
- 4