gpt4 book ai didi

javascript - 如何计算具有元素值的对象?

转载 作者:行者123 更新时间:2023-11-29 19:18:14 25 4
gpt4 key购买 nike

我需要你的帮助。我有这样的数组:

  var array = [{
"name": "Tony",
"year": "2010"
}, {
"name": "Helen",
"year": "2010"
}, {
"name": "Jack",
"year": "2005"
}, {
"name": "Tony",
"year": "2008"
}, {
"name": "Max",
"year": "2005"
}];

我如何按年计算它们并得到这样的结果:

2010 = 2 times;
2005 = 2 times;
2008 = 1 time;

谢谢

最佳答案

检查这个fiddle

var countObj = {};
for( var counter = 0; counter < array.length; counter++ )
{
var yearValue = array [ counter ].year;
if ( !countObj[ yearValue ] )
{
countObj[ yearValue ] = 0;
}
countObj[ yearValue ] ++;
}
console.log( countObj );

关于javascript - 如何计算具有元素值的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34352799/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com