Andy5
Andy5

Reputation: 2405

Retrieving an Array of Data from Props

I am trying to retrieve an array of data which is in a JSON format, and is passed to a React Component. If I use console.log(props), I can see data as follows: { props: {data: [[array]]}}.

The problem I have is that I am not able to drill down into the actual data. I have tried props.data.map and props.map, and both of theses return undefined.

The JSON format is as follows:

someData = {
             data: [
                     [
                       { 'id':'1',
                         'name': 'somename'
                        }
                     ]
                   ]
            }

Is there another object that I need to drill down to get to the data?

Upvotes: 1

Views: 902

Answers (3)

arslan
arslan

Reputation: 1144

let data = JSON.parse(someData)
data.forEach(element => {
  element.map(item => {
    return item
  })
})

if you are exact know there is only one item in array then use somedata.data[0].item; but parse json first because json is strigfy when we recieve json

Upvotes: 0

user120242
user120242

Reputation: 15268

The object structure is layered differently than you were expecting. It is encapsulated within an additional object with another props property, and the inner array is wrapped in another array.
props.props.data[0].map

Upvotes: 1

Rajat Verma
Rajat Verma

Reputation: 307

The problem here is that the Data is in JSON format and to retrieve and use the the data in JavaScript, you have to parse it into a JavaScript Object. You can simply do that using the JSON.parse() method to parse it into a object. Just pass the prop into this object before sending it and it will work as expected then.

data = JSON.parse(data); // if it was defined using let keyword

Then just pass it to the required component.
You can learn more about JSON.parse() from here

Upvotes: 3

Related Questions