简体   繁体   English

使用新键创建新数组并从单个数组嵌套 object

[英]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:我正在尝试从返回以下 json 的 api 组织数据:

[
  {
    "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. api 返回一个数组,其中只有数字作为键,下一个日期开始后为空 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.您可以为每个 object 创建一个数组,并检查所有 vlaues 是空字符串还是最后两个。

The continue or build a new date object and add later all events to the last object.继续或构建一个新日期 object 并稍后将所有事件添加到最后一个 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; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM