Home > Blockchain >  How to access nested object from Strapi using JS
How to access nested object from Strapi using JS

Time:10-13

I am trying to retrive some data from nested object.

This is the consle.log() result:

  console.log("bg data", data)
{
"pageLayouts": {
    "data": [
        {
            "attributes": {
                "title": "a title",
                "layout": "home",
                "backgroundImage": {
                    "data": [
                        {
                            "attributes": {
                                "alternativeText": "bg image",
                                "url": "image url",
                                "__typename": "UploadFile"
                            },
                            "__typename": "UploadFileEntity"
                        }
                    ],
                    "__typename": "UploadFileRelationResponseCollection"
                },
                "__typename": "PageLayout"
            },
            "__typename": "PageLayoutEntity"
        }
    ],
    "__typename": "PageLayoutEntityResponseCollection"
}

}

![enter image description here What i need is the URL.

What i tried:

const backgroundImage = attributes?.pageLayouts?.data?.attributes.backgroundImage.data?.attributes?.url

plz if anyone knows what i am missing here. Thanks

CodePudding user response:

Erhm, if console.log(data); outputs what you posted, then you should use data:

const backgroundImage = data?.pageLayouts?.data?.attributes.backgroundImage.data?.attributes?.url

CodePudding user response:

The data objects are Arrays but you are trying to read the properties as if it was just an object. You can still use unknown (?.) identifiers, you just need to do so on the array indices as such:

 const backgroundImage = attributes?.pageLayouts?.data?.[0]?.attributes.backgroundImage.data?.[0]?.attributes?.url

Note the addition of ?.[0] to both data objects.

  • Related