简体   繁体   中英

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 🚀🚀

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 🌟🌟

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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