在 React JS 中将 API 响应(对象)转换为数组

Convert API response (object) to array in react JS

正在尝试使用 mui 数据表。已设法使用示例数据来使用它。 我想更改它而不是我的示例数据值,以便我使用来自 API 的响应,即 this.props.meeting.

API 回复 >> this.props.meetings

"2021-07-06T00:00:00Z" : [ {
      "type" : "meeting",
      "name" : "Test JP morgan asia meeting",
      "agenda" : "<p>Test</p>",
      "location" : "Test",
      "startOn" : "2021-07-06T07:14:52.563Z",
      "endOn" : "2021-07-06T08:14:52.563Z",
    } ],
"2021-07-01T00:00:00Z" : [ {
      "type" : "meeting",
      "name" : "Future meeting",
      "agenda" : "<p>This is a test meeting session</p>",
      "location" : "Asia",
      "startOn" : "2021-07-01T06:13:00.000Z",
      "endOn" : "2021-07-01T06:54:00.000Z",
    } ]
 

完整组件

class Meeting extends React.Component {
  constructor(props) {
    super(props);
    ...
  }


  render() {
    const {
      meetings,
    } = this.props;
    console.log(this.props.meetings);

    const columns = ['Date', 'Time', 'Title', 'Location', 'Published'];
    const data = [
      ['4 Jul 2021', '12:00PM - 1:00PM', 'Lunch catch up with CEO of MS', 'Test', 'No'],
      ['4 Jul 2021', '2:00PM - 3:00PM', 'Meeting with ICBC Chairman', 'Test', 'No'],
      ['5 Jul 2021', '4:00PM - 5:00PM', 'Discussion with JP Morgan Head of APAC', 'Test', 'No'],
    ];

    const options = {
      ...
    };

    return (
      <MUIDataTable
        title="Meetings"
        data={data}
        columns={columns}
        options={options}
      />
    );
  }
}

....

我不确定这是否是您要查找的内容。 看看我的代码。 首先,您需要创建一个与所有会议长度相同的新数组(具有等效的日期键)。 然后您需要展平数组以便仅获取值,然后将它们与日期键合并。

    let meetings = {
    "2021-07-06T00:00:00Z" : [ {
          "type" : "meeting",
          "name" : "Test JP morgan asia meeting",
          "agenda" : "<p>Test</p>",
          "location" : "Test",
          "startOn" : "2021-07-06T07:14:52.563Z",
          "endOn" : "2021-07-06T08:14:52.563Z",
        } ],
    "2021-07-01T00:00:00Z" : [ {
          "type" : "meeting",
          "name" : "Future meeting",
          "agenda" : "<p>This is a test meeting session</p>",
          "location" : "Asia",
          "startOn" : "2021-07-01T06:13:00.000Z",
          "endOn" : "2021-07-01T06:54:00.000Z",
        } , {
          "type" : "meeting2",
          "name" : "Future meeting2",
          "agenda" : "<p>This is a test meeting session</p>",
          "location" : "Asia",
          "startOn" : "2021-07-01T06:13:00.000Z",
          "endOn" : "2021-07-01T06:54:00.000Z",
        } ]
    }
    
let arr1 = []

Object.entries(meetings).forEach(ar => ar[1].forEach(ar1 => arr1.push([ ar[0], ar1 ])))

console.log('FINAL ARRAY', arr1.map(obj => [obj[0], Object.values(obj[1])].flat()))
console.log('WITH SLICE', arr1.map(obj => [obj[0], Object.values(obj[1])].flat()).map(arr => arr.slice(0, arr.length - 1)))

首先,检查你是 this.props.meetings 对象,它是否包含你提供的相同定义,如果是,那么它将自动呈现并由它自己的 mui 数据表处理。