我正在获取一个对象数组(原始数据),通过displayName获取值,然后通过displayName将其插入(const defaultCirclePackStructure),这是用于d3圆包装。这是Codepen

let convertMetricDataToD3 = (arrayMetricData) => {
  var circlePackData = defaultCirclePackStructure
  let operationSumTime = 0

  arrayMetricData.forEach(element => {
    insertMetricData(element, circlePackData)
    if(element.displayName === "Equipment Uptime" || element.displayName === "Equipment  Downtime"){
      operationSumTime+=element.value
    }
  });

  circlePackData.children[0].children[1].value =
Math.round(operationSumTime) + "%"
  return circlePackData;
}


它可以工作,但是它是如此脆弱且效率低下,我如何通过使用map,reduce,filter或其他方法来改进它。

最佳答案

摆脱您的笔,我能够创建以下内容,这些内容更具可维护性。

const convertMetricDataToD3 = (arrayMetricData) => {

  const circlePackData = defaultCirclePackStructure;
  arrayMetricData.forEach(element => insertMetricData(element, circlePackData));

  const trackedOperations = [
    'Equipment Uptime',
    'Equipment Downtime',
  ];

  const operationSumTime = arrayMetricData
    .filter(({displayName}) => trackedOperations.includes(displayName))
    .map(({value})=> value)
    .reduce((a, b) => a + b);

  circlePackData.children[0].children[1].value = Math.round(operationSumTime) + "%";

  return circlePackData;
}

09-30 19:25