给出标题:
row.push({"ticker" : PX_Hist[j]['ticker']});
使用不同时间段参数计算数据
const timeframes = [5,10,90,120,250,500];
for (let t = 0; t <= timeframes.length - 1; t++){
row.push({"move" : ((PX_Hist[j]['px'][PX_Hist[j]['px'].length-1]["adjusted_close"] / PX_Hist[j]['px'][PX_Hist[j]['px'].length-timeframes[t]]["adjusted_close"] -1))});
}
我正在用这段代码创建以下输出。
[
[
{
"ticker": "JPM"
},
{ "move": 0.01405944118170499 },
{ "move": 0.0337445573294628 },
{ "move": 0.1692882281117576 },
{ "move": 0.07636499188035195 },
{ "move": 0.8151371865267423 },
{ "move": 0.4537049320855997 }
],
[
{
"ticker": "C"
},
{ "move": -0.01295986622073586 },
{ "move": 0.002689694224235595 },
{ "move": 0.05544868117343582 },
{ "move": -0.0457495911125243 },
{ "move": 0.7837535634777528 },
{ "move": 0.05665004788714745 }
],
[
{
"ticker": "C"
},
{ "move": -0.01295986622073586 },
{ "move": 0.002689694224235595 },
{ "move": 0.05544868117343582 },
{ "move": -0.0457495911125243 },
{ "move": 0.7837535634777528 },
{ "move": 0.05665004788714745 }
],
]
我需要将上面的数组转换为可以轻松绑定到如下表的数组:
[{"ticker": "JPM", "5": 0.01405944118170499,"10": 0.0337445573294628,"90":
0.1692882281117576,"120": 0.07636499188035195,"250": 0.8151371865267423,"500":
0.4537049320855997}]
关于如何以优雅的方式做到这一点,有什么建议吗?
您可以使用map和for循环来实现类似的功能。但老实说,我觉得这没必要。你可以从一开始就这样做。你可以试试:
row[0][timeframes[t]] = "that long thing you have there"
const arr = [
[{
"ticker": "JPM"
},
{
"move": 0.01405944118170499
},
{
"move": 0.0337445573294628
},
{
"move": 0.1692882281117576
},
{
"move": 0.07636499188035195
},
{
"move": 0.8151371865267423
},
{
"move": 0.4537049320855997
}
],
[{
"ticker": "C"
},
{
"move": -0.01295986622073586
},
{
"move": 0.002689694224235595
},
{
"move": 0.05544868117343582
},
{
"move": -0.0457495911125243
},
{
"move": 0.7837535634777528
},
{
"move": 0.05665004788714745
}
],
[{
"ticker": "C"
},
{
"move": -0.01295986622073586
},
{
"move": 0.002689694224235595
},
{
"move": 0.05544868117343582
},
{
"move": -0.0457495911125243
},
{
"move": 0.7837535634777528
},
{
"move": 0.05665004788714745
}
],
]
const flatObj = (arr) => {
const flatObject = {};
const keys = ["ticker", "5", "10", "90", "120", "250", "500"]
for (let i = 0; i < arr.length; i++) {
for (const property in arr[i]) {
flatObject[keys[i]] = arr[i][property];
}
};
return flatObject;
}
const result = arr.map(ar => flatObj(ar))
console.log(result)