I have received below array of objects as a response from Rest API,
var companyDatas = {
"accounts": {
"company 1 ": {
"id": "4",
"enabled": "1"
},
"company 2": {
"id": "2",
"enabled": "1"
},
"company 3": {
"id": "1",
"enabled": "1"
}
}
};
const [companyData, setcompanyData] = useState([companyDatas]);
But i have a difficulty rendering below array of objects as following format.
company 1
id:4
company 2
id:2
company 3
id:1
so far i have tried below code ,where response is the list of json i have received from rest api via post. response.accounts
which gives me below list of objects, but now i am not able to display only comapany name and id ..
"company 1 ": {
"id": "4",
"enabled": "1"
},
"company 2": {
"id": "2",
"enabled": "1"
},
"company 3": {
"id": "3",
"enabled": "1"
}
As @technophyle commented, please share what you're tried next time. I assumed that object is stored in some sort of variable, I've called it companyData
for now.
Here's how you would achieve your desired output
export default function App() {
const companyDatas = {
"accounts": {
"company 1 ": {
"id": "4",
"enabled": "1"
},
"company 2": {
"id": "2",
"enabled": "1"
},
"company 3": {
"id": "1",
"enabled": "1"
}
}
};
const [companyData, setCompanyData] = useState(companyDatas)
return (
<View style={styles.container}>
{
Object.entries(companyData.accounts)
.map(([company, accountData]) => (
<View key={company}>
<Text>{company}</Text>
<Text>id: {accountData.id}</Text>
</View>
))
}
</View>
);
}
Using Object.entries()
will give you an array of company objects as such:
[
[
"company 1 ",
{
"id": "4",
"enabled": "1"
}
],
[
"company 2",
{
"id": "2",
"enabled": "1"
}
],
[
"company 3",
{
"id": "1",
"enabled": "1"
}
]
]
Then using .map(([company, accountData]))
we can assign the data to these variables. Then you simply use those as {company}
and {accountData}
in your JSX.
Edit:
I didn't notice the useState earlier. First I'd like to ask why companyData
is stored as useState([companyData])
, because that's why it's giving that error. Removing the []
from it will fix it.