简体   繁体   中英

Is it possible to cast a Typescript object with named keys to an array?

I am working with React + Typescript and an external API which I have no control over.

I have an API response that looks like the following:

{
  data: {
    "0": {
      id: "1a",
      label: "Label 1"
    },
    "1": {
      id: "2ab",
      label: "Label 2"
    }
  }
}

in which the API response will always be an object of named keys incrementing from 0 upwards, much like an array.

When this data is fetched, I use the following type to store the data:

export type dataType = {
  [index: string]: {
    id: string;
    label: string;
  };
};

However since it is technically an object instead of an array, I can't iterate over the data when trying to display it in React.

Something like

  const data: dataType = useFetchData()
  data.map((item) => {
    console.log(item);
  })

results in a map is not a function error such as below, since it is technically an object:

Type '{ "0": { id: string; label: string; }; "1": { id: string; label: string; }; }' is missing the following properties from type '{ id: string; label: string; }[]': length, pop, push, concat, and 29 more

I was wondering if it is possible to "cast" the object to an array to make use of the array functions provided by javascript or what is the best way of converting one to another?

I tried converting the dataType to an array and using that however it gives the same error.

Since the response.data keys are same as the array indices you could just use Object.values to map your data object values into an array.

 const res = { data: { "0": { id: "1a", label: "Label 1" }, "1": { id: "2ab", label: "Label 2" } } }; const resArr = Object.values(res.data); console.log(resArr);

But then you may also change your dataType to be an object and use it as array of type like:

export type dataType = {
    id: string;
    label: string;
};

const data: dataType[] = Object.values(res.data);

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