简体   繁体   中英

How to represent in typescript a list of objects where the key is the date and the content is an array?

I am racking my brain to represent the following data set in typescript: 在此处输入图片说明

I'm trying as follows, but I get an error in ReactJs.

interface IDose {
  name: string;
  date: string;
}

interface IVaccine {
  [date: string]: IDose[]
}

const [data, setData] = useState<IVaccine[]>([]);

...

<IonGrid>
  <IonRow>
    {data.map((d, i) => {
      return (
        <IonCol key={i}>
          <IonButton>
            {d.date}
            <br />
            {d.name}
          </IonButton>
        </IonCol>
      );
    })}
  </IonRow>
</IonGrid>

Error: Uncaught TypeError: data.map is not a function...

Could anyone give me any suggestions?

First, create a new object class for your array object.

export class Object {
    name: string;
    date: string; //or Date
}

then, create the data structure

let objectMap : Map<string (date string), Object[]> = new Map<string, Object[];

However...do you need an additional date field when the key is already the date? I feel like you can simply use the key as the date for the named field.

I do see a few issues with your code.

First and foremost, the data state does not seem to be an array of object, thus Array.map() won't work if you wish to iterate through the keys and print their respective values. Therefore, if you wish to iterate through data and print the values within it, you might want to use Object.values() instead. That being said, you should define the typings for state as an object (dictionary), rather than an array of objects.

This are the changes you should make:

interface IDose {
  name: string;
  date: string;
}

interface IVaccine {
  [date: string]: IDose[]
}

// here
const [data, setData] = useState<IVaccine>();

...

<IonGrid>
  <IonRow>
    // and here
    {data && Object.values(data).map((d, i) => {
      return (
        <IonCol key={i}>
          <IonButton>
            {d.date}
            <br />
            {d.name}
          </IonButton>
        </IonCol>
      );
    })}
  </IonRow>
</IonGrid>

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