[英]“Clean” an array inside another array of objects in JavaScript
I'm currently struggling with a task, hope somebody can guide me in the right direction.我目前正在为一项任务而苦苦挣扎,希望有人能指导我朝着正确的方向前进。
I have this array:我有这个数组:
const data = [
{
year: 2021,
data: [
{ month: 'Jan', amount: 5000000 },
{ month: 'Feb', amount: 3500000 },
{ month: 'Mar', amount: 15000000 },
{ month: 'Apr', amount: 5000000},
{ month: 'May', amount: 3500000 },
{ month: 'Jun', amount: 15000000 },
{ month: 'Jul', amount: 13000000 },
{ month: 'Aug', amount: 20000000 }
]
},
{
year: 2020,
data: [
{ month: 'Jan', amount: 5000000 },
{ month: 'Feb', amount: 3500000 },
{ month: 'Mar', amount: 15000000 },
{ month: 'Apr', amount: 5000000},
{ month: 'May', amount: 3500000 },
{ month: 'Jun', amount: 15000000 },
{ month: 'Jul', amount: 13000000 },
{ month: 'Aug', amount: 20000000 }
]
}
] ]
And I'm trying to clean this so I can use HighCharts JS, which needs the following structure:我正在尝试清理它,以便我可以使用 HighCharts JS,它需要以下结构:
const data = [
{ year: '2021',
data: [5000000, 3500000, 15000000, 5000000, 3500000, 15000000, 13000000, 20000000 ]
},
{ year: '2020',
data: [5000000, 3500000, 15000000, 5000000, 3500000, 15000000, 13000000, 20000000 ]
}
]
So basically, is to clean the data array inside each object to get only the amount value without the month name.所以基本上,就是清理每个对象内部的数据数组,只得到没有月份名称的金额值。 I tried doing a map and storage the result in a useState (I'm working with React JS) with no success.
我尝试制作地图并将结果存储在 useState(我正在使用 React JS)中,但没有成功。
Any idea would be highly appreciated.任何想法将不胜感激。
Try this:试试这个:
data.map(({ year, data: innerData }) => ({
year,
data: innerData.map(({ amount }) => amount)
}))
You can map each object and replace the data array with a mapped data array inside a {...}
spread您可以映射每个对象并将数据数组替换为
{...}
扩展中的映射数据数组
const data = [ { year: 2021, data: [ { month: 'Jan', amount: 5000000 }, { month: 'Feb', amount: 3500000 }, { month: 'Mar', amount: 15000000 }, { month: 'Apr', amount: 5000000}, { month: 'May', amount: 3500000 }, { month: 'Jun', amount: 15000000 }, { month: 'Jul', amount: 13000000 }, { month: 'Aug', amount: 20000000 } ] }, { year: 2020, data: [ { month: 'Jan', amount: 5000000 }, { month: 'Feb', amount: 3500000 }, { month: 'Mar', amount: 15000000 }, { month: 'Apr', amount: 5000000}, { month: 'May', amount: 3500000 }, { month: 'Jun', amount: 15000000 }, { month: 'Jul', amount: 13000000 }, { month: 'Aug', amount: 20000000 } ] }] const newdata = data.map(e=> ({...e, data: e.data.map(x=>x.amount)})) console.log(newdata)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.