如何在自动完成中填充嵌套数组的值 Material UI

how to populate values of nested array in Auto Complete Material UI

我有一个包含嵌套数组的对象数组,

 [
  {
    code:1234,
    componentData:[{
       title:'B123456',
       Dates:'02-07-2021'
      }]
   }
 ]

现在我想使用 Material UI 和 Reactjs 将这些值作为选项填充到自动完成组件的下拉列表中。我浏览了 docs,每个示例都有一个简单的对象数组,这不是我要找的。我想弄清楚如何在自动完成的下拉选项中同时显示 titleDates。 然后尝试触发 onchange 函数并获取用户 Select 上的 titleDates 值。

https://codesandbox.io/s/material-demo-forked-8k9hu?file=/demo.js 代码沙箱 Link : Code

是这样的:

如果我理解正确,你想显示嵌套的 componentData 选项,给定一个对象数组,这些对象都包含 componentData。如果是这样,您可以使用 flatMap 将嵌套数组数据转换为单个选项数组,例如:

  const data =  [
    {
      code: 1234,
      componentData: [
        {
          title:'B123456',
          Dates:'02-07-2021'
        },
        {
          title:'B789',
          Dates:'02-08-2021'
        },
      ]
    },
    {
      code: 2345,
      componentData: [
        {
          title:'B234567',
          Dates:'02-07-2021'
        },
      ]
    }
  ];
  
  // `options` will be an Array of length 3 (for the 3 nested options above)
  const options = data.flatMap(object => object.componentData);

  // Render autocomplete given the `options`, where you define whatever `onChange` handler you need
  // to access the `title` and `Dates`, and provide a `renderOption` prop to choose how to present
  // the data as an option in your UI
  return (
    <Autocomplete
      options={options}
      onChange={(event, newValue) => {
        if (newValue) {
          console.log(newValue.title);
          console.log(newValue.Dates);
        }
      }}
      renderInput={(params) => <TextField {...params} label="Combo box" variant="outlined" />}
      renderOption={(option) => <Typography>{option.title} - {option.Dates}</Typography>}
    />
  );