Home > Net >  How can I fetch data from a REST API where field names vary and how to type it in typescript?
How can I fetch data from a REST API where field names vary and how to type it in typescript?

Time:09-06

I've had trouble fetching an API because an object field name can vary from one object to another, as well as the number of children of this same object:

[
  {
    "name": {
      "common": "Finland",
      "official": "Republic of Finland",
      "nativeName": {
        "fin": {
          "official": "Suomen tasavalta",
          "common": "Suomi"
        },
        "swe": {
          "official": "Republiken Finland",
          "common": "Finland"
        }
      }
    }
  },
  {
    "name": {
      "common": "Guatemala",
      "official": "Republic of Guatemala",
      "nativeName": {
        "spa": {
          "official": "República de Guatemala",
          "common": "Guatemala"
        }
      }
    }
  }
]

Here nativeName's first child can be spa or fin depending on the object, and there can be one or two (and even more in other instances) children.

How can I get to the first nativeName's common value here ?

Also, how can I type this data in typescript ? So far, I left it as such :

type name = {
  name: {
    common: string,
    official: string,
    nativeName: {
      var1: {
        official: string,
        common: string
      },
      var2: {
        official: string,
        common: string
      }
    }
  }
}

Thanks in advance.

Edit: I realize I have one last question:

"languages": {
      "spa": "Spanish"
    }

here spa varies as well as the number of entries in languages, how would I type that in typescript?

CodePudding user response:

first question:

const nameObj =  {
    "name": {
      "common": "Finland",
      "official": "Republic of Finland",
      "nativeName": {
        "fin": {
          "official": "Suomen tasavalta",
          "common": "Suomi"
        },
        "swe": {
          "official": "Republiken Finland",
          "common": "Finland"
        }
      }
    }
  }

const firstCommon = Object.values(nameObj.name.nativeName)[0].common

second question:

type name = {
  name: {
    common: string,
    official: string,
    nativeName: {
      [key: string]: {
        official: string,
        common: string
      }
    }
  }
}
  • Related