首页 > 解决方案 > 将数组转换为单个数组,并将键分配给对象值

问题描述

我有嵌套的对象格式,其中没有分配给值的键,格式如下所示:

{
  "data": {
    "2019": {
      "January": {
        "complaintRaised": 9,
        "totalPending": 4,
        "totalClosed": 0,
        "resolvedPercent": 0
      }
    },
    "2018": {
      "May": {
        "complaintRaised": 9,
        "totalPending": 4,
        "totalClosed": 0,
        "resolvedPercent": 0
      }
    }

  },

}

我需要将其转换为带有键的单个数组

response.data: [{
    key: "2019"
    "complaintRaised": 9,
    "totalPending": 4,
    "totalClosed": 0,
    "resolvedPercent": 0
    year: "2019-January"
  },
  {
    key: "2018"
    "complaintRaised": 9,
    "totalPending": 4,
    "totalClosed": 0,
    "resolvedPercent": 0
    year: "2018-May"
  }
]

分配给值。

标签: angular

解决方案


如果同一年有超过一个月的时间,第一个答案将不起作用,如下例所示。此代码将处理所有月份。

const dataInput = {
  "data": {
    "2019": {
      "January": {
        "complaintRaised": 9,
        "totalPending": 4,
        "totalClosed": 0,
        "resolvedPercent": 0
      },
      "March": {
        "complaintRaised": 91,
        "totalPending": 41,
        "totalClosed": 10,
        "resolvedPercent": 10
      }
    },
    "2018": {
      "May": {
        "complaintRaised": 9,
        "totalPending": 4,
        "totalClosed": 0,
        "resolvedPercent": 0
      }
    }
  }
}

const response = {
  data: Object.entries(dataInput.data).reduce((res, [year, val]) => ([
    ...res, 
    ...Object.entries(val).reduce((res2, [month, val2]) => ([
      ...res2,
      {
        key: year,
        ...val2,
        year: `${year}-${month}`
      }
    ]), []),
  ]), [])
};

console.log(response);


推荐阅读