我需要构建图表, 有一个包含图表数据对象的数组
"graphicDetails": [
{
"hour": 0,
"businessOperationPlansTotalDemand": 8.201753196882908,
"employeesCount": 0,
"businessOperationPlans": [
{
"name": "operation0",
"value": 5.999355066255491
},
]
},
{
"hour": 1,
"businessOperationPlansTotalDemand": 7.450044665662842,
"employeesCount": 3,
"businessOperationPlans": []
},
{
"hour": 2,
"businessOperationPlansTotalDemand": 5.814536267254451,
"employeesCount": 5,
....
要在图表库 (chartjs) 中绘制它,我需要该对象包含字段{x: hour, y:businessOperationPlansTotalDemand, etc.}
。示例:
data: [
{ x: 0, y: 5.815634, businessOperationPlans: [{operation: ...}] ,
{ x: 1, y: 2.23232, businessOperationPlans: [{operation2: ...}] ,
...
]
我知道我可以使用 forEach 或类似的东西来重命名属性,但是解决此任务的正确方法是什么?也许我应该要求后端以其他格式制作数据?
也许我需要基于此与其他属性创建一个新数组并将其放入 Vue 中的计算字段中?我该怎么做?
最佳答案
您可以使用map
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
const graphicDetails = [{
"hour": 0,
"businessOperationPlansTotalDemand": 8.201753196882908,
"employeesCount": 0,
"businessOperationPlans": [{
"name": "operation0",
"value": 5.999355066255491
}, ]
},
{
"hour": 1,
"businessOperationPlansTotalDemand": 7.450044665662842,
"employeesCount": 3,
"businessOperationPlans": []
}
];
const newData = graphicDetails.map(a=>{
return {x:a.hour,y:a.businessOperationPlansTotalDemand,businessOperationPlans:a.businessOperationPlans };
})
console.log(newData);
关于javascript - 如何重命名数组中对象的属性。解决任务的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57584821/