我有一個要轉換的物件陣列。它包含如下嵌套物件結構:
[
{
geography: 'Austia',
product: 'RTD Coffee',
dataType: 'Off-Trade rsp (curr/con, local)',
timeSeries: [
{
year: 2017,
value: 0.148891823777856,
highlight: 1,
},
{
year: 2018,
value: 0.148965642232877,
highlight: 1,
},
{
year: 2019,
value: 0.149039460687898,
highlight: 1,
},
{
year: 2020,
value: 0.149113279142919,
highlight: 1,
},
{
year: 2021,
value: 0.149187097597941,
highlight: 1,
},
{
year: 2022,
value: 0.149260916052962,
highlight: 1,
},
],
},...
];
我想將其轉換為以下模式,其中提取 TimeSeries 陣列物件屬性并將其映射到頂層,如下所示:
[
{
geography: 'Austria',
product: 'RTD Coffee',
dataType: 'Off-Trade rsp (curr/con, local)',
2017: 0.148891823777856,
2018: 0.148965642232877,
2019: 0.149039460687898,
2020: 0.149113279142919,
2021: 0.149187097597941,
2022: 0.149260916052962,
},
]
我該怎么做?
uj5u.com熱心網友回復:
嘗試這個
function extractYearValue(arr) {
return arr.map(({timeSeries, ...element}) => {
const objYearValue = timeSeries.reduce((prev, curr) => {
return {...prev, [curr.year]: curr.value}
}, {})
return {...element, ...objYearValue}
})
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/535836.html
上一篇:用一個onclick和querySelectorAll()改變兩個div的屬性
下一篇:呈現過去12個月的資料模板
