简体   繁体   中英

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:

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

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

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