Search code examples
arraysjsonobjectnext.jsstrapi

Remove parent array and object elements from json - Strapi


Currently building an API with Strapi with the model of a blog post such that each Post has a Title, Slug, Content, and user Relation.

What data looks like:

{
  "data": [
    {
      "id": 1,
      "attributes": {
        "title": "Test1",
        "createdAt": "2022-07-24T18:33:34.195Z",
        "updatedAt": "2022-07-24T18:33:34.863Z",
        "publishedAt": "2022-07-24T18:33:34.861Z",
        "user": {
          "data": {
            "id": 1,
            "attributes": {
              "username": "xyz",
              "email": "[email protected]",
              "provider": "local",
              "confirmed": false,
              "blocked": false,
              "createdAt": "2022-07-24T14:28:16.466Z",
              "updatedAt": "2022-07-24T14:29:00.126Z"
            }
          }
        }
      }
    }
  ],
}

What I want it to look like:

{
    {
      "id": 1,
      "title": "Test1",
      "createdAt": "2022-07-24T18:33:34.195Z",
      "updatedAt": "2022-07-24T18:33:34.863Z",
      "publishedAt": "2022-07-24T18:33:34.861Z",
      "user": {
         "id": 1,
         "username": "xyz",
         "email": "[email protected]",
         "provider": "local",
         "confirmed": false,
         "blocked": false,
         "createdAt": "2022-07-24T14:28:16.466Z",
         "updatedAt": "2022-07-24T14:29:00.126Z"
        }
    }
}

By default, the data is wrapped in unnecessarily tiresome arrays and objects and any attempt to edit the scehma.json causes the API to crash.

How can I fix this?


Solution

  • you can try this solution :

    const x = {
      "data": [
        {
          "id": 1,
          "attributes": {
            "title": "Test1",
            "createdAt": "2022-07-24T18:33:34.195Z",
            "updatedAt": "2022-07-24T18:33:34.863Z",
            "publishedAt": "2022-07-24T18:33:34.861Z",
            "user": {
              "data": {
                "id": 1,
                "attributes": {
                  "username": "xyz",
                  "email": "[email protected]",
                  "provider": "local",
                  "confirmed": false,
                  "blocked": false,
                  "createdAt": "2022-07-24T14:28:16.466Z",
                  "updatedAt": "2022-07-24T14:29:00.126Z"
                }
              }
            }
          }
        }
      ],
    }
    const data = x.data[0]
    const users = {id: data.attributes.user.data.id , ...data.attributes.user.data.attributes}
    const result = {id: data.id , title: data.attributes.title , createdAt: data.attributes.createdAt ,  updatedAt: data.attributes.updatedAt , publishedAt: data.attributes.publishedAt , user: users }
    ```