Home > Mobile >  can I pick a grandchild value directly in object without being through parent value?
can I pick a grandchild value directly in object without being through parent value?

Time:07-18

I need to pick up value from a returned API object, the hierarchy is like this

{"name":
       {"common":"Germany",
        "official":"Federal Republic of Germany",
        "nativeName":
             {"deu":
                {"official":"Bundesrepublik Deutschland",
                 "common":"Deutschland"}}},
  "currencies":
        {"EUR":
             {"name":"Euro",
              "symbol":"€"}}

I want to pick up "Deutschland", so I write like name.nativeName.deu.common , but the problem is by each different user input, the country name changes each time, and "deu" and "EUR" also will be different, in this example, is that a way that I can pick up the value "common" under "nativeName" and "name" under "currencies", without going through their parents "deu" and "EUR"?

CodePudding user response:

It looks like the API may return a response with multiple keys on both nativeName and currencies, so here's an example that returns all values as array.

const apiResponse = {
  "name": {
    "common": "Germany",
    "official": "Federal Republic of Germany",
    "nativeName": {
      "deu": {
        "official": "Bundesrepublik Deutschland",
        "common": "Deutschland"
      }
    }
  },
  "currencies": {
    "EUR": {
      "name": "Euro",
      "symbol": "€"
    }
  }
}

const nativeNames = Object.keys(apiResponse.name.nativeName).map(key => {
  return apiResponse.name.nativeName[key].common;
});

const currencies = Object.keys(apiResponse.currencies).map(key => {
  return apiResponse.currencies[key].name;
});

console.log(nativeNames);
console.log(currencies);

  • Related