我想更新对象以仅显示最近一年,每年仅显示一个。
当前股息变量为:
const data = {
0: [
'AAPL',
0.378571,
'2012-09-30'
],
1: [
'AAPL',
0.378571,
'2012-12-31'
],
2: [
'AAPL',
0.378571,
'2013-03-31'
],
3: [
'AAPL',
0.435714,
'2013-09-30'
],
4: [
'AAPL',
0.435714,
'2013-12-31'
],
5: [
'AAPL',
0.47,
'2014-09-30'
],
6: [
'AAPL',
0.47,
'2014-12-31'
],
7: [
'AAPL',
0.52,
'2015-06-30'
],
8: [
'AAPL',
0.52,
'2015-09-30'
],
9: [
'AAPL',
0.52,
'2015-12-31'
]
};
我想将变量更新为:
const dividends = {
0: [
'AAPL',
0.378571,
'2012-12-31'
],
1: [
'AAPL',
0.435714,
'2013-12-31'
],
2: [
'AAPL',
0.47,
'2014-12-31'
],
3: [
'AAPL',
0.52,
'2015-12-31'
]
};
抱歉,必须删除代码块格式,因为 stackoverflow 由于错误而不允许我发帖
最佳答案
您可以使用array#reduce
根据对象中最早日期的年份对数据进行分组。然后使用Object.values()
获取所有值。
const data = { 0: [ 'AAPL', 0.378571, '2012-09-30' ], 1: [ 'AAPL', 0.378571, '2012-12-31' ], 2: [ 'AAPL', 0.378571, '2013-03-31' ], 3: [ 'AAPL', 0.435714, '2013-09-30' ], 4: [ 'AAPL', 0.435714, '2013-12-31' ], 5: [ 'AAPL', 0.47, '2014-09-30' ], 6: [ 'AAPL', 0.47, '2014-12-31' ], 7: [ 'AAPL', 0.52, '2015-06-30' ], 8: [ 'AAPL', 0.52, '2015-09-30' ], 9: [ 'AAPL', 0.52, '2015-12-31' ] },
result = Object.values(data).reduce((r,a) => {
let year = a[2].substr(0,4);
r[year] = r[year] || [...a];
r[year] = r[year][2] > a[2] ? r[year]: [...a];
return r;
},{});
const dividends = {...Object.values(result)};
console.log(dividends);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 如何对年份进行分组并减少对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54625343/