vinuta
vinuta

Reputation: 423

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.

Upvotes: 1

Views: 57

Answers (2)

Muhammed Albarmavi
Muhammed Albarmavi

Reputation: 24472

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

Upvotes: 1

Andriy
Andriy

Reputation: 15472

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

Upvotes: 1

Related Questions