简体   繁体   English

Javascript:计算数组中所有 object 值的总和

[英]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;如果键是A,它的值必须乘以30,B乘以10,C乘以5,D乘以2。我想计算乘法后的总和;

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

Is there a way to achieve this other than an if/else statement?除了 if/else 语句之外,还有其他方法可以实现吗? 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.减少数组,并通过在每个项目上调用Object.entries()来解构数组生成的键/值对。 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您可以使用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}您可以创建一个字典来获取应该与该值相乘的数字,如下所示: {"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:现在您可以遍历对象数组,并使用 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 .不确定您如何 map 您的值,以便"A" === 30 But assuming you have a map:但假设你有一个 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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