JavaScript format nested data structure

For my latest project, I am working on a blog using Strapi combined with Nuxt. To fetch the categories and articles data for my blog, I send a JSON object from my front-end application using Axios.

{
    "data": [
        {
            "id": 1,
            "attributes": {
                "createdAt": "2022-01-06T17:43:01.152Z",
                "updatedAt": "2022-01-06T17:43:03.326Z",
                "publishedAt": "2022-01-06T17:43:03.323Z",
                "name": "Législation",
                "articles": {
                    "data": [
                        {
                            "id": 2,
                            "attributes": {
                                "title": "Décrets",
                                "createdAt": "2022-01-06T18:52:24.828Z",
                                "updatedAt": "2022-01-06T20:48:29.434Z",
                                "publishedAt": "2022-01-06T18:52:26.644Z"
                            }
                        },
                        {
                            "id": 1,
                            "attributes": {
                                "title": "Lois",
                                "createdAt": "2022-01-06T18:52:03.115Z",
                                "updatedAt": "2022-01-06T20:48:38.850Z",
                                "publishedAt": "2022-01-06T18:52:09.058Z"
                            }
                        }
                    ]
                }
            }
        },
        {
            "id": 2,
            "attributes": {
                "createdAt": "2022-01-06T17:43:53.562Z",
                "updatedAt": "2022-01-06T17:43:55.735Z",
                "publishedAt": "2022-01-06T17:43:55.733Z",
                "name": "Militaires",
                "articles": {
                    "data": [
                        {
                            "id": 3,
                            "attributes": {
                                "title": "Base de données",
                                "createdAt": "2022-01-06T19:07:51.206Z",
                                "updatedAt": "2022-01-06T20:48:07.248Z",
                                "publishedAt": "2022-01-06T19:07:53.737Z"
                            }
                        }
                    ]
                }
            }
        },
        {
            "id": 3,
            "attributes": {
                "createdAt": "2022-01-06T17:44:06.082Z",
                "updatedAt": "2022-01-06T17:44:06.568Z",
                "publishedAt": "2022-01-06T17:44:06.567Z",
                "name": "Régiments",
                "articles": {
                    "data": []
                }
            }
        },
        {
            "id": 4,
            "attributes": {
                "createdAt": "2022-01-06T17:45:04.262Z",
                "updatedAt": "2022-01-06T17:45:05.226Z",
                "publishedAt": "2022-01-06T17:45:05.223Z",
                "name": "Vie militaire",
                "articles": {
                    "data": []
                }
            }
        }
    ],
    "meta": {
        "pagination": {
            "page": 1,
            "pageSize": 25,
            "pageCount": 1,
            "total": 4
        }
    }
}

To structure this data within my Nuxt application, I want to create a nested object that captures the categories and their respective articles in a specific format:

{
  {
    "name": "Législation",
    "article": [
                { 
                 "title": "Lois",
                 "createdAt": "2022-01-06T18:52:24.828Z"
                },
                { 
                 "title": "Décrets",
                 "createdAt": "2022-01-06T18:52:03.115Z"
                }
               ]
  },
  {
    "name": "Militaires",
    "article": [
                { 
                 "title": "Base de données",
                 "createdAt": "2022-01-06T19:07:51.206Z"
                }
               ]
  }

}

However, dealing with this nested data structure presents its own set of challenges. Any tips or suggestions on how to manage this efficiently?

Answer №1

const rawData = {
        "data": [
            {
                "id": 1,
                "attributes": {
                    "createdAt": "2022-01-06T17:43:01.152Z",
                    "updatedAt": "2022-01-06T17:43:03.326Z",
                    "publishedAt": "2022-01-06T17:43:03.323Z",
                    "name": "Legal Matters",
                    "articles": {
                        "data": [
                            {
                                "id": 2,
                                "attributes": {
                                    "title": "Decrees",
                                    "createdAt": "2022-01-06T18:52:24.828Z",
                                    "updatedAt": "2022-01-06T20:48:29.434Z",
                                    "publishedAt": "2022-01-06T18:52:26.644Z"
                                }
                            },
                            {
                                "id": 1,
                                "attributes": {
                                    "title": "Laws",
                                    "createdAt": "2022-01-06T18:52:03.115Z",
                                    "updatedAt": "2022-01-06T20:48:38.850Z",
                                    "publishedAt": "2022-01-06T18:52:09.058Z"
                                }
                            }
                        ]
                    }
                }
            },
            {
                "id": 2,
                "attributes": {
                    "createdAt": "2022-01-06T17:43:53.562Z",
                    "updatedAt": "2022-01-06T17:43:55.735Z",
                    "publishedAt": "2022-01-06T17:43:55.733Z",
                    "name": "Military Stuff",
                    "articles": {
                        "data": [
                            {
                                "id": 3,
                                "attributes": {
                                    "title": "Database",
                                    "createdAt": "2022-01-06T19:07:51.206Z",
                                    "updatedAt": "2022-01-06T20:48:07.248Z",
                                    "publishedAt": "2022-01-06T19:07:53.737Z"
                                }
                            }
                        ]
                    }
                }
            },
            {
                "id": 3,
                "attributes": {
                    "createdAt": "2022-01-06T17:44:06.082Z",
                    "updatedAt": "2022-01-06T17:44:06.568Z",
                    "publishedAt": "2022-01-06T17:44:06.567Z",
                    "name": "Regiments",
                    "articles": {
                        "data": []
                    }
                }
            },
            {
                "id": 4,
                "attributes": {
                    "createdAt": "2022-01-06T17:45:04.262Z",
                    "updatedAt": "2022-01-06T17:45:05.226Z",
                    "publishedAt": "2022-01-06T17:45:05.223Z",
                    "name": "Military Life",
                    "articles": {
                        "data": []
                    }
                }
            }
        ],
        "meta": {
            "pagination": {
                "page": 1,
                "pageSize": 25,
                "pageCount": 1,
                "total": 4
            }
        }
    }
    
    const formattedData = []
    rawData.data.forEach(entry =>  {
      if(entry.attributes.articles.data.length) {
          formattedData.push({
            name: entry.attributes.name,
            articles: entry.attributes.articles.data.map(article => {
              return {
                title: article.attributes.title,
                createdAt: article.attributes.createdAt
              }
            })
          })
      }
      
    })

    console.log(formattedData)

Answer №2

To manipulate the data, utilize the map method

const transformedData = rawData.map(item =>  { return {title: item.attributes.title, posts: item.attributes.posts}})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to updating information inside of script tags in html using javascript

Within my HTML, there is a script tag that looks like this: <script type="application/ld+json"> { "@context": "http://schema.org", "@type": "VideoObject", "name": "Title", "description": "Video descrip ...

What causes the body onload = javascript function to run repeatedly?

Greetings for the absolute beginners out there, just dipping your toes in AJAX. I'm curious to know what exactly triggers the continuous change in divMessage content when the text "myName" is altered. 1) It appears that the Javascript function proce ...

Issue with rendering components list in React.js

I am currently working on a project using React, and I'm facing an issue where my list is not displaying on render(). In my parent component, I have a list of components coming from SearchResult. Below is the relevant portion of my code: class Create ...

Comparison of Uint8Array and Uint8ClampedArray

Can you explain the distinction between Uint8Array and Uint8ClampedArray within JavaScript? I've heard that Uint8ClampedArray is specifically utilized for pixel manipulations on canvas. Could you elaborate on why this array type is recommended for suc ...

There was a syntax error found in the JSON input when $.ajax() was utilized, resulting in

I'm currently working on a website that requires implementing a chat feature. The project is running locally, but I've encountered an error: SyntaxError: Unexpected end of JSON input Despite searching online for a solution, nothing seems to w ...

When attempting to remove an object from an array in Vue.js, an error may occur stating that the property of the

In my project, I am working with 3 files: App, BlogList, BlogItem. The goal is to enable users to delete a post if they choose to. However, when using splice method, I encountered the following error: The property or method "removePost" is not defined o ...

Obtain the latest NPM package versions

I am currently seeking a way to compile a comprehensive list of all major versions that have been released for a specific NPM package. By utilizing the following API link, I can retrieve a list of available versions which includes both the major and exper ...

Issue with Discord.js voice connection destruction函数

I've been attempting to implement a "Stop" command using the @discordjs/voice package, but I'm encountering an error. Despite my efforts to add some error handling, the issue persists. Below is the code snippet: async function stop(message) { t ...

Switching on and off a class in Next.js

I'm a beginner with Next.js and React framework. My question is regarding toggling a class. Here's my attempt in plain JS: function toggleNav() { var element = document.getElementById("nav"); element.classList.toggle("hidde ...

determining the overall page displacement

I'm working with this code and I need help using the IF condition to check if the total page offset is greater-than 75%. How can I implement that here? function getLocalCoords(elem, ev) { var ox = 0, oy = 0; var first; var pageX, pageY; ...

Is there a way to detect when the escape key is pressed?

Is there a way to detect when the escape key is pressed in Internet Explorer, Firefox, and Chrome? I have code that works in IE and alerts 27, but in Firefox it alerts 0 $('body').keypress(function(e){ alert(e.which); if(e.which == 27){ ...

Iterate through the entire array without including a specific item

I am struggling with looping through an array of items and applying some code to each item while excluding one specific item (the clicked-on item). I have experimented with using splice, but that method ends up removing the array item completely, whereas I ...

Combining Multiple Arrays into a Multidimensional Array

I'm struggling to find information on how to combine multiple arrays of the same length into a multidimensional array. For example, I have three arrays: array1 = [value1a1, value2a1, value3a1]; array2 = [value1a2, value2a2, value3a2]; array3 = [value ...

What is the method for determining the size of a WeakMap?

I am working with a WeakMap that looks like the following: let newObj = new WeakMap(); let key1={"a":1}; let key2={"b":2}; let key3={"c":3}; newObj.set(key1,"value1"); newObj.set(key2,"value2"); newObj.set( ...

What is the best way to access the text content of a nested HTML element for automation tasks with Selenium or Protractor?

Can anyone help me with this HTML code snippet? I want to extract and display only the text within the desc class - "Print this", ignoring the text in the spell class. This needs to be done using either Protractor or Selenium. <span class="desc"> Pr ...

Modal obstructing BsDatePicker

<!-- The Server Modal --> <div class="modal" id="serverModal"> <div class="modal-dialog" style="max-width: 80%;overflow-y: initial !important;" > <div class=" ...

Automatically submitting forms without having to refresh the page

I have been searching for answers online, but none of them seem to help me. Additionally, I am struggling to grasp the concept of Ajax. I need everything to happen on a single page without any refreshing until the entire form is submitted. <form id=" ...

Limit the vertical movement in Vue drag and drop operations

Currently, I am working on a project that involves implementing drag-and-drop functionality using vue-draggable. You can find more information about it here: https://github.com/SortableJS/Vue.Draggable. I am facing an issue where the height of the element ...

Steps for installing a package using npm without the need for configuring a package.json file

According to this source, it is feasible to install npm packages before creating the package.json file. After installing nodeJS on my computer, I attempted to run the following command in an empty directory: npm install jQuery This resulted in the follow ...

Utilize Google Autofill to easily populate address fields in a form

I've come across several autofill address codes, but I'm looking to integrate a Post function that would allow me to post the obtained data to a PHP page. Is there anyone who can assist with the javascript or HTML code to achieve this? HTML Cod ...