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

Create new array with new keys and nested object from single array

I’m trying to organise data from an api that returns the following json:

[
  {
    "0": "THURSDAY 25th MARCH",
    "1": "",
    "2": ""
  },
  {
    "0": "Snow Patrol",
    "1": "Press Conference",
    "2": "16:00 - 19:35"
  },
  {
    "0": "",
    "1": "",
    "2": ""
  },
  {
    "0": "FRIDAY 26th MARCH",
    "1": "",
    "2": ""
  },
  {
    "0": "Arctic Moneys",
    "1": "Concert",
    "2": "11:55 - 12:40"
  },
  {
    "0": "Rush",
    "1": "Practice Session",
    "2": "13:05 - 13:50"
  }
]

The api returns an array with only numbers as keys and the next date starts after and empty object.

Into an organised array like so:

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

[
  {
    "date": "THURSDAY 25th MARCH",
    "events": [
      {
        "band": "Snow Patrol",
        "type": "Press Conference",
        "time": "16:00 - 19:35"
      }
    ]
  },
  {
    "date": "FRIDAY 26th MARCH",
    "events": [
      {
        "band": "Arctic Moneys",
        "type": "Concert",
        "time": "11:55 - 12:40"
      },
      {
        "band": "Rush",
        "type": "Practice Session",
        "time": "13:05 - 13:50"
      }
    ]
  }
]

Any help would be much appreciated!

Cheers!

>Solution :

You could create an array of each object and check if all vlaues are empty strings or the last two ones.

The continue or build a new date object and add later all events to the last object.

const
    data = [{ 0: "THURSDAY 25th MARCH", 1: "", 2: "" }, { 0: "Snow Patrol", 1: "Press Conference", 2: "16:00 - 19:35" }, { 0: "", 1: "", 2: "" }, { 0: "FRIDAY 26th MARCH", 1: "", 2: "" }, { 0: "Arctic Moneys", 1: "Concert", 2: "11:55 - 12:40" }, { 0: "Rush", 1: "Practice Session", 2: "13:05 - 13:50" }],
    result = data.reduce((r, o) => {
        const a = Object.assign([], o);
        if (!a.join('')) return r;
        if (!a.slice(1).join('')) {
            r.push({ date: a[0], events: [] });
        } else {
            const [band, type, time] = a;
            r[r.length - 1].events.push({ band, type, time });
        }
        return r;
    }, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
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