Rizwan
Rizwan

Reputation: 3666

JSON parsing in React Native to get Array of String

In react native in the following JSON I need to get an array of string ["abc description", "def description", "ghi description" and so on] for value of DataHolder. There could be n number of dictionary in DataHolder

{
  "StatusCode": 200,
  "Description": "Description",
  "Message": "Success",
  "Response": {
    "Data": {
      "DataHolder": [
        {
          "abc": "abc description"
        },
        {
          "def": "def description"
        },
        {
          "ghi": "ghi description"
        }
      ]
    }
  }
}

I am new in react-native any help will be appreciated.

Upvotes: 0

Views: 898

Answers (2)

Muhammad Iqbal
Muhammad Iqbal

Reputation: 1495

One solution would be using JSON library

 const tempJSON = {
      "StatusCode": 200,
      "Description": "Description",
      "Message": "Success",
      "Response": {
        "Data": {
          "DataHolder": [
            {
              "abc": "abc description"
            },
            {
              "def": "def description"
            },
            {
              "ghi": "ghi description"
            }
          ]
        }
      }
    }

    let resultJSON = JSON.stringify(tempJSON)
    resultJSON = JSON.parse(resultJSON)

    console.log(resultJSON.Response.Data.DataHolder)

log result

(3) [{…}, {…}, {…}]
0: {abc: "abc description"}
1: {def: "def description"}
2: {ghi: "ghi description"}

Upvotes: 0

wdm
wdm

Reputation: 7189

Sounds like you would just like to restructure the data from an API response. Here is one solution:

const data = {
    ...
    "Response": {
        "Data": {
            "DataHolder": [
                {
                    "abc": "abc description"
                },
                {
                    "def": "def description"
                },
                {
                    "ghi": "ghi description"
                }
            ]
        }
    }
};
const descriptions = data.Response.Data.DataHolder.map(item => Object.values(item)[0]);

// ["abc description", "def description", "ghi description"]

Upvotes: 2

Related Questions