数据的处理:获取id,处理两级数组

87 阅读1分钟
const backData = [
  {
    "id": 0,
    "plan_id": 1,
    "plan_exec_time": "2022-09-09 16:00:00",
    "business_id": 1,
    "fault_name": "数据零",
    "dependent_plan_ids": [],
    "arrange_type": 1
  },
  {
    "id": 1,
    "plan_id": 1,
    "plan_exec_time": "2022-09-09 17:00:00",
    "business_id": 1,
    "fault_name": "数据一",
    "dependent_plan_ids": [0],
    "arrange_type": 1
  },
  {
    "id": 2,
    "plan_id": 1,
    "plan_exec_time": "2022-09-09 18:00:00",
    "business_id": 2,
    "fault_name": "数据二",
    "dependent_plan_ids": [0, 1],
    "arrange_type": 1
  },
  {
    "id": 3,
    "plan_id": 1,
    "plan_exec_time": "2022-09-09 19:00:00",
    "business_id": 3,
    "fault_name": "数据三",
    "dependent_plan_ids": [],
    "arrange_type": 1
  },
  {
    "id": 4,
    "plan_id": 4,
    "plan_exec_time": "2022-09-09 20:00:00",
    "business_id": 3,
    "fault_name": "数据4",
    "dependent_plan_ids": [0, 3],
    "arrange_type": 1
  },
  {
    "id": 5,
    "plan_id": 4,
    "plan_exec_time": "2022-09-09 21:00:00",
    "business_id": 3,
    "fault_name": "故障名称5",
    "dependent_plan_ids": [2, 3],
    "arrange_type": 1
  },
  {
    "id": 6,
    "plan_id": 4,
    "plan_exec_time": "2022-09-09 22:00:00",
    "business_id": 3,
    "fault_name": "故障名称5",
    "dependent_plan_ids": [2, 5],
    "arrange_type": 1
  }
]


function handleData(arr) {
  const result = [];
  const mapper = {};
  const len = arr.length
  for (let i = 0; i < len; i++) {
    const item = arr[i];
    const temp = [];
    const depLen = item.dependent_plan_ids.length
    if (depLen) {
      for (let j = depLen - 1; j > -1; j--) {
        const value = item.dependent_plan_ids[j];
        if (temp.findIndex(item => item.id === value) > -1) {
          continue;
        }
        if (mapper[value]) {
          temp.push(...mapper[value]);
        }
      }
    }
    temp.sort((a, b) => new Date(a.plan_exec_time).getTime() - new Date(b.plan_exec_time).getTime())
    temp.push(item);
    mapper[item.id] = temp;
    result.push(temp);
  }
  return result
}

const res = handleData(backData)
console.log(res)