我想以投資組合為基礎合并績效資料。
const data = {"portfolio": {"name": "portfolio 1","performance": [{"date": "2022-01-01","value": 100},{"date": "2022-01-15","value": 150}, {"date": "2022-02-01","value": 200}],"funds": [{"name": "fund 1","performance": [{"date": "2022-01-01","value": 3}, {"date": "2022-02-01","value": 4}],},{"name": "fund 2","performance": [{"date": "2022-01-01","value": 5}, {"date": "2022-02-01","value": 6}, {"date": "2022-03-01","value": 7}]}]}};
const {name, performance, funds} = data.portfolio;
const result = {
headers: ["date", name, ... funds.map(({name}) => name)],
data: funds[0].performance.map(({date, value}, i) =>
[date, performance[i].value, ...funds.map(({performance: {[i]: {value}}}) => value)]
)
};
console.log(result);
當前結果:
{
data: [["2022-01-01", 100, 3, 5], ["2022-02-01", 150, 4, 6]],
headers: ["date", "portfolio 1", "fund 1", "fund 2"]
}
預期結果:
{
headers: ["date", "portfolio 1", "fund 1", "fund 2"],
data: [["2022-01-01", 100,3, 5], ["2020-01-15", 150, , ], ["2022-02-01", 200, 4, 6]]
}
請注意,它不包括“2022-03-01”,因為投資組合沒有它。
JSFiddle:https ://jsfiddle.net/mkdeveloper2021/o30nbf6j/9/
uj5u.com熱心網友回復:
在這種結構中,每個基金的表現陣列不一定具有與全域表現陣列相同的長度,匹配的條目不會出現在相同的索引處,并且必須按日期顯式匹配。
換句話說,解構引數的部分{[i]: {value}}需要用不同的解決方案替換。您必須找到正確的索引。我建議使用find:
const data = {"portfolio": {"name": "portfolio 1","performance": [{"date": "2022-01-01","value": 100}, {"date": "2022-01-15","value": 150}, {"date": "2022-02-01","value": 200}], "funds": [{"name": "fund 1","performance": [{"date": "2022-01-01","value": 3}, {"date": "2022-02-01","value": 4}],},{"name": "fund 2","performance": [{"date": "2022-01-01","value": 5}, {"date": "2022-02-01","value": 6}],}]}};
const {name, performance, funds} = data.portfolio;
const result = {
headers: ["date", name, ...funds.map(({name}) => name)],
data: performance.map(({date, value}, i) =>
[date, value, ...funds.map(({performance}) =>
performance.find(item => item.date == date)?.value
)]
)
};
console.log(result);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/448638.html
標籤:javascript
