1

JSON payload how to find a key/value equal to a value provided

In a project which consume an API I receive a JSON payload as follow:

{
  "data": {
    "study": {
      "id": "DEM1",
      "locales": [
        {
          "locale": "en_IT",
          "language": {
            "direction": "ltr"
          }
        },
        {
          "locale": "en_US",
          "language": {
            "direction": "ltr"
          }
        }
      ]}

From this JSON I need to find with JS the locale en_US and output the "direction": "ltr".

The locale is arriving inside a method where this JSON is get and I need to extract the right part of it which corresponding of the en_US.

I got a difficulty how to do that in this situation

Submitted October 06th 2021 by Admin

Answers
0

Using Array#find:

const obj = { "data": { "study": { "id": "DEM1", "locales": [ { "locale": "en_IT", "language": { "direction": "ltr" } }, { "locale": "en_US", "language": { "direction": "ltr" } } ] } }
}; const { language } = obj?.data?.study?.locales?.find(({ locale }) => locale === "en_US") || {}; console.log(language);

Admin | 1 week ago



Relevant Questions