I want to access the title
inner object of the following object, which I am getting from WP REST API. But I am unable to reach the 'title'.
The REST API returns me an object, not an array because I am consuming an ID-based API endpoint i.e. https://example.com/wp/wp-json/v2/procedures/7
.
The above gives me the following JSON:
{
"id": 7,
"date": "2023-06-08T11:39:59",
"date_gmt": "2023-06-08T11:39:59",
"guid": {
"rendered": "https://example.com/?post_type=procedure&p=7"
},
"modified": "2023-06-09T05:45:45",
"modified_gmt": "2023-06-09T05:45:45",
"slug": "best-hydra-facial-treatment",
"status": "publish",
"type": "procedure",
"link": "https://example.com/procedure/best-hydra-facial-treatment/",
"title": {
"rendered": "Best Hydra Facial Treatment"
},
...
...
}
I want to get the rendered
key value from the title
inner object. So I tried proc.title.rendered
(proc is the object here). But this gives me the error proc.title.rendered is not defined
.
What is the correct way of doing it?
const data = {
"id": 7,
"date": "2023-06-08T11:39:59",
"date_gmt": "2023-06-08T11:39:59",
"guid": {
"rendered": "https://example.com/?post_type=procedure&p=7"
},
"modified": "2023-06-09T05:45:45",
"modified_gmt": "2023-06-09T05:45:45",
"slug": "best-hydra-facial-treatment",
"status": "publish",
"type": "procedure",
"link": "https://example.com/procedure/best-hydra-facial-treatment/",
"title": {
"rendered": "Best Hydra Facial Treatment"
}
}
console.log(data?.guid?.rendered)
console.log(data.title.rendered)
console.log(data?.title?.rendered)
above code is log "rendered key".
in case at your object, some sub object has title obj
& rendered key
. if some of them do not have the key, that can be error.
in that case, could you try ? in front of dot notation
data?.title?.rendered