我想将对象更新为仅显示最近的一年,每年仅显示一次。
当前的股息变量为:
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不允许我发帖,因此不得不删除代码块格式
答案 0 :(得分:1)
您可以使用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; }
答案 1 :(得分:0)
希望对您有帮助。
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'
]
};
var years=[];
var result={};
var count=0;
for(var key in data){
var arr=data[key];
var year=arr[2].split("-")[0];
if(years.indexOf(year)==-1){
years.push(year);
result[count]=arr;
count++;
}
}
console.log(result);
答案 2 :(得分:0)
您可以使用Object.values()
将对象转换为数组,.filter()
来检查原始数组Boolean
的{{1}}日期字符串元素的.some()
是否倒置对象Date
等于迭代的当前元素,.getFullYear()
大于当前元素,并且.getMonth()
大于或等于当前元素,将结果数组传递到.getDate()
将每个数组设置为JavaScript普通对象的基于0的属性
Object.assign()
答案 3 :(得分:0)
您可以从右侧按日期减少排序的数据,并每年收集一次,仅对一个数据集进行分组。
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'] },
years = {},
result = Object.assign({}, Object.assign([], data).reduceRight((r, a) => {
if (!years[a[2].slice(0, 4)] && !r.find(b => [0, 1].every(i => a[i] === b[i]))) {
r.push(a);
years[a[2].slice(0, 4)] = true;
}
return r;
}, []).reverse());
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }