简体   繁体   中英

Javascript: calculate the total sum of all the object values in an array

I have an array of objects as the following;

[{"A":"34"},{"B":"13"},{"C":"35"},{"D":"74"}]

If the key is A, it's value has to be multiply by 30,B by 10,C by 5,D by 2. I would like to calculate the total sum after the multiplication;

34*30 + 13*10 + 35*5 + 74*2

Is there a way to achieve this other than an if/else statement? Thanks!

 let input = [{"A": "34"}, {"B": "13"}, {"C": "35"}, {"D": "74"}]; let multiply = {A: 30, B: 10, C: 5, D: 2}; let result = input.reduce((sum, v) => sum + Object.values(v)[0] * multiply[Object.keys(v)[0]], 0); console.log(result);

Reduce the array, and get the key / value pair by destructuring the array produce by calling Object.entries() on the each item. Get the value of the key, multiply by current value, and add to the accumulator.

 const multi = { A: 30, B: 10, C: 5, D: 2 } const fn = arr => arr.reduce((acc, item) => { const [[k, v]] = Object.entries(item) return acc + multi[k] * v }, 0) const arr = [{"A":"34"},{"B":"13"},{"C":"35"},{"D":"74"}] const result = fn(arr) console.log(result)

You can easily achieve this using Object.entries

 const arr = [{ A: "34" }, { B: "13" }, { C: "35" }, { D: "74" }]; const multiplier = { A: 30, B: 10, C: 5, D: 2, }; const result = arr.reduce((acc, curr) => { const [[key, value]] = Object.entries(curr); return acc + multiplier[key] * parseInt(value); }, 0); console.log(result);

You can create an dictionary to get the number with which the value should be multiplied as shown: {"A":30, "B":13, "C":35, "D":74}

Now you can loop through your array of objects, and fetch the value from the dictionary using the key of the object:

const myArray = [{"A":"34"},{"B":"13"},{"C":"35"},{"D":"74"}]
const Nums = {"A":30, "B":10, "C":5, "D":2};
let Result = 0;

myArray.forEach((item)=>{
  const key = Object.keys(item)[0];
  var temp= parseInt(item[key]);
  Result += temp*Nums[key];
})
console.log(Result);

Not sure how you map your values so that "A" === 30 . But assuming you have a map:

const map = {
  "A": 30,
  "B": 10,
  "C": 5,
  "D": 2
}

const array = [{"A":"34"},{"B":"13"},{"C":"35"},{"D":"74"}];

Then in one line:

const outcome = array.map(element => map[Object.keys(element)[0]] * Object.values(element)[0]).reduce((acc, init) => acc + init, 0)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM