jarivak
jarivak

Reputation: 858

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

I have an array of Objects which includes an nested array ,

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

Now i want to populate these values as option in dropdown of auto complete component using Material UI and Reactjs. I went through the docs and every example has a simple array of objects, which is not what I'm looking for. I'm trying to figure out how to show both title and Dates in the dropdown options of autocomplete. And then try to fire the onchange function and get both title and Dates values on Select by the user.

https://codesandbox.io/s/material-demo-forked-8k9hu?file=/demo.js Code Sandbox Link : Code

Something like this : Output I am trying to achieve

Upvotes: 1

Views: 1648

Answers (1)

Steven D.
Steven D.

Reputation: 700

If I understand correctly, you'd like to show the nested componentData options, given an array of objects which all contain componentData. If that's right, you can use a flatMap to convert your nested array data to a single array of options, like:

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

Upvotes: 2

Related Questions