Reputation: 1812
I'm new to React-Native, therefore, Javascript and I'm trying to understand how I can retrieve this data to be filled in my FlatList. The JSON format I receive looks like this
[
{
"18": {
"sellingUnitName": "unité(s)",
"qualifier": "GOOD",
"sizeQualifierName": "gr.20"
},
"19": {
"sellingUnitName": "unité(s)",
"qualifier": "BAD",
"sizeQualifierName": "gr.18-20"
}
}
]
Here's what my FlatList looks like
<FlatList
data={ this.state.dataSource }
ItemSeparatorComponent = {this.FlatListItemSeparator}
renderItem={({item}) => <Text>{item.sellingUnitName}</Text>}
keyExtractor={(item, index) => index.toString()}
/>
If the format is like this, my FlatList is working well
[
{
"sellingUnitName": "unité(s)",
"qualifier": "GOOD",
"sizeQualifierName": "gr.20"
},
{
"sellingUnitName": "unité(s)",
"qualifier": "BAD",
"sizeQualifierName": "gr.18-20"
}
]
My question is: how can I manage to use the first format by looping through each item and ignoring the first id (for example "18" in the first example) so that I can use item.keyName in my FlatList to display each values? It seems like I need to get the nested element but I can't figure out how to do this.
And if needed, this is how I fetch my data
fetch('https://www.mywebsite.com/test.php')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
dataSource: responseJson
};
})
.catch((error) => {
console.error(error);
});
Thanks!
Upvotes: 1
Views: 1985
Reputation: 13892
By using Object.keys
and Array.map
we can get the data to look like you want.
let data = [
{
"18": {
"sellingUnitName": "unité(s)",
"qualifier": "GOOD",
"sizeQualifierName": "gr.20"
},
"19": {
"sellingUnitName": "unité(s)",
"qualifier": "BAD",
"sizeQualifierName": "gr.18-20"
}
}
];
let dataObj = data[0];
let dataArray = Object.keys(dataObj).map(key => {
let obj = dataObj[key];
obj.keyName = key;
return obj;
})
console.log(dataArray)
After this, dataArray will look like [{keyName: 18, sizeQualifierName: "gr.20", ...}, {keyName: 19, sizeQualifierName:"gr.18-20", ...}]
Upvotes: 2