Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Split Object to array of objects

I want to separate the object below into two objects following the year in the keys.

const a = {
  "id": "2",
  "2019_progrSin": "2",
  "2019_percResponsabilita": "30",
  "2019_flag": "B",
  "2019_tipoResponsabilitaSinistro": "O",
  "2019_anno": "2019",
  "2019_codComp": "O",
  "2018_progrSin": "2",
  "2018_percResponsabilita": "50",
  "2018_flag": "Y",
  "2018_tipoResponsabilitaSinistro": "I",
  "2018_anno": "2018",
  "2018_codComp": "O"
}

I want obtain b from a, like:

const b = [
 {
   "2019_progrSin": "2",
   "2019_percResponsabilita": "30",
   "2019_flag": "B",
   "2019_tipoResponsabilitaSinistro": "O",
   "2019_anno": "2019",
   "2019_codComp": "O",
 },
 {
   "2018_progrSin": "2",
   "2018_percResponsabilita": "50",
   "2018_flag": "Y",
   "2018_tipoResponsabilitaSinistro": "I",
   "2018_anno": "2018",
   "2018_codComp": "O"
 }
]

The property can be more. ( like "2017_flag" / "2016_flag" and so on)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Using Array.prototype.reduce, Object.values, and Object.entries. This would also work:

const input = {
  id: "2",
  "2019_progrSin": "2",
  "2019_percResponsabilita": "30",
  "2019_flag": "B",
  "2019_tipoResponsabilitaSinistro": "O",
  "2019_anno": "2019",
  "2019_codComp": "O",
  "2018_progrSin": "2",
  "2018_percResponsabilita": "50",
  "2018_flag": "Y",
  "2018_tipoResponsabilitaSinistro": "I",
  "2018_anno": "2018",
  "2018_codComp": "O",
};

const output = Object.values(
  Object.entries(input).reduce((prev, [key, value]) => {
    const [year] = key.split("_");
    if (!isNaN(year)) {
      if (!prev[year]) {
        prev[year] = {};
      }
      prev[year][key] = value;
    }
    return prev;
  }, {})
);

console.log(output);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading