简体   繁体   English

如何通过键 select 数组中的所有对象并将它们的值相加?

[英]How to select all objects within an array by their key and add their values together?

So here's what I'm trying to do, I have an application I've been working on that allows users to read articles and take quizzes on them, each article is contained in a category.所以这就是我正在尝试做的事情,我有一个我一直在开发的应用程序,它允许用户阅读文章并对其进行测验,每篇文章都包含在一个类别中。 Category has an _id which is unique.类别有一个唯一的 _id。 Quiz attempts are held within another table which refrences the article, which refrences the category.测验尝试保存在另一个引用该文章的表中,该文章引用了该类别。

I have looped through all of the quiz attempts and store their keys and values in an array of objects which looks like the following:我已经遍历了所有的测验尝试,并将它们的键和值存储在一个对象数组中,如下所示:

const userScoreArray = [];
   for(let i = 0; i < data[1].length; i++) {
     userScoreArray.push({[data[1][i]['dataValues']['article_id']]: data[1][i]['dataValues']['score']  }) // overall
   }

Now I have an array which stores quiz attempts for each category:现在我有一个数组来存储每个类别的测验尝试:

[
{4: 5},
{4: 1},
{3: 6},
{5: 0}
// { category: score }
]

How would I be able to get into this array, select all objects with the key of "4" and and then add all of their values together, and then again grab all objects with the key of "5" and add their values together?我怎样才能进入这个数组,select 所有对象的键为“4”,然后将它们的所有值加在一起,然后再次使用键“5”抓取所有对象并将它们的值加在一起? I was thinking of using a loop to do it but my brain starts to steam right then.我正在考虑使用循环来做到这一点,但我的大脑马上就开始沸腾了。

You can use an Array.reduce iterator, then Object.keys() and Object.values() to extract the numbers for comparing and adding您可以使用Array.reduce迭代器,然后使用Object.keys()Object.values()来提取用于比较和添加的数字

 let data = [ {4: 5}, {4: 1}, {3: 6}, {5: 0} // { category: score } ]; const getScoreFor = n => { return data.reduce((b, a) => { return b + (Object.keys(a)[0] == n? Object.values(a)[0]: 0); }, 0); } console.log(getScoreFor(4))

You can use the reduce method as follows:您可以使用 reduce 方法,如下所示:

const array = [{ 4: 5 }, { 4: 1 }, { 3: 6 }, { 5: 0 }];
const accArray = array.reduce((acc, obj) => {
  if (obj[4] ?? obj[5]) {
    acc += Object.values(obj)[0];
  }
  return acc;
 }, 0);

console.log(accArray); // 6

MDN ref.: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce MDN 参考: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

By using reduce(), you loop through the array having access at each iteration to an accumulator, the current element and the current index.通过使用reduce(),您可以循环访问在每次迭代时可以访问累加器、当前元素和当前索引的数组。 The initial value of the accumulator, on the above example, is set to zero;在上面的例子中,累加器的初始值设置为零; at each iteration, we check if the object has a key equal to 4 or 5;在每次迭代中,我们检查 object 的密钥是否等于 4 或 5; if the condition is true we add to the accumulator the value of that object, then it is returned the accumulator (because that is how the reduce method works).如果条件为真,我们将 object 的值添加到累加器,然后返回累加器(因为这是 reduce 方法的工作原理)。

OBS: I used the nullish coalescing operator (??) just in case you need to use 0 as key ({0: any_value}), as the or operator (||) works with falsy values. OBS:我使用了 nullish 合并运算符 (??) 以防您需要使用 0 作为键 ({0: any_value}),因为 or 运算符 (||) 适用于虚假值。

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

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