如何重命名数组中对象的属性。解决任务的正确方法是什么?

How to rename properties in objects that are in an array. What is the right way to solve the task?

我需要构建图表, 有一个包含图表数据对象的数组

"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);