如何计算 javascript 对象中的值?

How to count values in a javascript object?

我想获取所有等于某个数字的值并计算每个对象的数量。

我的代码如下所示:

var countItems = {
    "aa":"70",
    "bb":"70",
    "cc":"80",
    "dd":"90",
    "ee":"90",
    "ff":"90"
}

现在我想做的是在下半场算一算。

比如有两个“70”,一个“80”,三个90。那么我可以给变量赋值:

var firstCounter  = ?? // 2
var secondCounter = ?? // 1
var thirdCounter  = ?? // 3

?? 是我不知道这里发生了什么。

如果它的结构与下面不同,我可以这样做:

let firstCounter = 0;
for (let i = 0; i < countItems.length; i++) {
  if (countItems[i].status === '70') firstCounter++;
}

let secondCounter = 0;
for (let i = 0; i < countItems.length; i++) {
  if (countItems[i].status === '80') secondCounter++;
}

let thirdCounter = 0;
for (let i = 0; i < countItems.length; i++) {
  if (countItems[i].status === '90') thirdCounter++;
}

但问题是,我的原始代码结构不是这样的,所以我不确定如何调整它。

如何计算原始列表 (var countItems) 中的项目,以便找出每个值是多少?

您可以使用 Object.values(countItems) 来获得如下所示的数组:["70","70","80","90","90","90"] 然后使用 for 循环有条件地增加您想要的任何计数器,或者使用类似 Array.reduce or Array.filter来计算你需要的元素。

您可以使用 reduce 创建一个计数哈希映射,如下所示:

const countItems = [
  { data: 'aa', status: '70' },
  { data: 'bb', status: '70' },
  { data: 'cc', status: '80' },
  { data: 'dd', status: '90' },
  { data: 'ee', status: '90' },
  { data: 'ff', status: '90' },
];

const countedHash = countItems.reduce((acc, curr) => {
  if (!acc[curr.status])
    acc[curr.status] = 1
  else
    acc[curr.status] += 1
  return acc
}, {})

/* print out the results */
console.log(countedHash)

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

您可以像这样访问对象键:

countItems["aa"] // it will return "70"

您也可以在对象上循环(如果您想像示例中那样做):

for (const item in countItems) {
    console.log(countItems[item])
    if (countItems[item] == "70") firstCounter++;
    
}

Object.values()reduce()都是正确的思路。综合起来...

var countItems = {
    "aa":"70",
    "bb":"70",
    "cc":"80",
    "dd":"90",
    "ee":"90",
    "ff":"90"
};

let counts = Object.values(countItems).reduce((acc, value) => {
  if (!acc[value]) acc[value] = 0;
  acc[value]++;
  return acc;
}, {});

let [theFirstValue, theSecondValue, theThirdValue] = Object.values(counts)

console.log(theFirstValue, theSecondValue, theThirdValue);

const countItems = [
  { data: 'aa', status: '70' },
  { data: 'bb', status: '70' },
  { data: 'cc', status: '80' },
  { data: 'dd', status: '90' },
  { data: 'ee', status: '90' },
  { data: 'ff', status: '90' },
]; 

var countValues = Object.values(countItems);
let obj ={}
for(let val of countValues){
  if(!obj[val.status]){
    obj[val.status] = 1
  }else{
    obj[val.status] += 1
  }
}
 console.log(obj)