Home > database >  Create new array with new keys and nested object from single array
Create new array with new keys and nested object from single array

Time:12-29

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:

[
  {
    "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!

CodePudding user response:

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

  • Related