Reputation: 19
I am new to React Native and I want to get the object value and print it in the Text but I am getting undefined is not an object (evaluating json['label'])
Below is the format:
[ {"id":"1","label":"abc","icon":{"uri":"imagepath"}}]
So for now I have store it and trying to save the label value in variable.
for(let i = 0; i < 4; i++){
const json=this.state.typeofCountry[i];
const originallable33 = json['label'];
marqueeItems.push(
<View>
<Text >
{originallable33}
</Text>
</View>
);
}
It would be very helpful if anyone explains me how to parse the array and object and get any specific value from it.
Upvotes: 0
Views: 241
Reputation: 184
It looks like you're trying to take an array of data and use it create a new array of components that use this data. Using a for
loop can be quite bulky and difficult to read so I think you should rather use the map
function.
This is how I would solve it:
// this.state.typeofCountry is an array so we
// can use the map function to iterate over it.
// The callback function passes each entry of the array as a parameter,
// you can name this parameter anything you want!
this.state.typeofCountry.map((country) => (
<View>
<Text >
{country.label}
</Text>
</View>
))
To read more about map and other really useful array functions, I recommend you head over to MDN to see what else you can use. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Hope that helps, happy coding!
Upvotes: 1
Reputation: 2673
this is due to this.state.typeofCountry[i]
returning undefined
(most likely due to i
being bigger than the array itself)
safely extract items without undefined errors by adding a simple null check -
for(let i = 0; i < 4; i++){
const json=this.state.typeofCountry[i]; // json could be undefined
if(json?.label){
// notice the ?. operator (this is called optional chaining)
// if true, "label" is present
const originallable33 = json['label'];
marqueeItems.push(
<View>
<Text>
{originallable33}
</Text>
</View>
);
}
Upvotes: 1