简体   繁体   English

将数组转换为单个数组,然后将键分配给对象值

[英]Convert an array to it to the single array and also assign key to the object values

I have nested Object Format in which there is no key assigned to the values, the format is shown below: 我有嵌套的对象格式,其中没有键分配给值,格式如下所示:

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

which I need to convert it into a single array with key 我需要用键将其转换为单个数组

 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" } ] 

assign to the values. 分配给值。

Something like this will solve this problem 这样的事情可以解决这个问题

function render({data}) {
const entries :any[] = Object['entries'](data);

const result = entries.map(yearData => {
  let key = yearData[0];
  let month = Object.keys(yearData[1])[0];
  let monthData = yearData[1][month];

  return {
    key,
    ...monthData,
    year : `${key}-${month}`
  }

})
return result;
}

stackblitz demo 🚀🚀 stackblitz演示 🚀🚀

Updated : 更新 :

in case we have many months 万一我们有很多个月

function render({ data }) {
  const entries: any[] = Object['entries'](data);
  return entries.map(([key, data]) =>
    Object.keys(data).map(month => ({
      key,
      ...data[month],
      year: `${key}-${month}`
    }))
  ).reduce((acc: any[], next: any[]) => acc.concat(next), [])
}

stackblitz demo 🌟🌟 stackblitz演示 🌟🌟

The first answer will not work in case there are more than one month for the same year like in the following example. 如果同一年有一个月以上的时间(如以下示例),则第一个答案将无效。 This code will process all the months. 此代码将处理所有月份。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM