Organize unstructured JSON data using a specific method

My service returns a JSON with irregular data structure as shown below:

dataFromService: [
    {
        event_data: '2021-03-18T15:20:31.314Z', // if !null = page
        event_category: 'news',
        event_title_en: 'page title',
    },
    {
        event_list_news_events_event_data: 'not null', // if !null = doc
        event_list_news_events: [
            { event_category: 'news' },
            { event_title: 'page title' }
        ],
        publication_date: '2021-02-12T15:20:31.314Z'
    }
    ...
]

The goal is to format the data using the following method:

newData: [
    {   
        itemType: 'page',
        itemCategory: 'news',
        itemTitle: 'page title',
        itemDate: '2021-03-18T15:20:31.314Z',                       
    },
    {   
        itemType: 'doc',
        itemCategory: 'event',
        itemTitle: 'doc title',
        itemDate: '2021-02-12T15:20:31.314Z',                       
    },
    ...
]

An approach to achieve this is demonstrated below:

var app = new Vue({
    el: '#app',
    data: function() {
        return {
            myList: []
        }
    },
    created () {
        this.dataSource();
    },
    methods: {
        dataSource: function() {
            for(var i = 0; i < this.dataFromService.length; i++) {
                let elem = {};

                if (this.dataFromService[i].event_data && this.dataFromService[i].event_data != null) {
                    elem['itemType'] = 'page';
                    elem['itemCategory'] = this.dataFromService[i].event_category;
                    elem['itemDate'] = this.dataFromService[i].event_data;
                    if (this.lang === 'en') {
                        elem['itemTitle'] = this.dataFromService[i].event_title_en;
                    }
                } else if (this.dataFromService[i].event_list_news_events_event_data && this.dataFromService[i].event_list_news_events_event_data != null) {
                    elem['itemType'] = 'doc';
                    elem['itemCategory'] = this.dataFromService[i].event_list_news_events.event_category;
                    elem['itemDate'] = this.dataFromService[i].publication_date;
                    elem['itemTitle'] = this.dataFromService[i].event_list_news_events.event_title;
                }

                this.myList.push(elem);
            }
            console.log('myList: ', JSON.stringify(this.myList));
        }
    }
});

There are questions regarding optimization such as better ways than using the for loop and the best way to call the method, whether in "created", "beforeMount", or "mounted" hooks.

Answer №1

Keep in mind that the following two conditions are essentially the same. The first condition checks if event_data has a truthy value, which covers non-null values, rendering the second condition unnecessary:

if (
  this.dataFromService[i].event_data &&
  this.dataFromService[i].event_data != null // already covered by 1st condition
) {...}

The same logic applies to:

if (
  this.dataFromService[i].event_list_news_events_event_data &&
  this.dataFromService[i].event_list_news_events_event_data != null // already covered by 1st condition
) {...}

Hence, you can eliminate the redundant second conditions from your code.

Your current code seems fine, but an alternative way to structure your loop is by utilizing Array.prototype.map on the dataFromService[] array to create a new array based on the original one. Consider moving the item formatting into separate utility functions (toPageItem and toDocsItem) which can be invoked when dealing with page or document items respectively. If neither case applies, return null. Utilize Array.prototype.filter on the resulting array to remove any null entries.

... (additional code snippets)

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

Do I have to divide the small functions in my Node.js controller into smaller ones?

When signing up users in my controller, do I need to break up the sign-up steps into individual asynchronous calls or is one big asynchronous call sufficient? Each step relies on the previous one: Validate user Create user Create group Add user to group ...

I'm encountering difficulties in utilizing Ajax to upload images

I have been attempting to utilize ajax and bootstrap (modal) to add a new product. However, when I click the save changes button, I encounter an issue where all fields return an error message stating 'Undefined index'. Below is the code snippet ...

Declaring a function within a conditional statement

I recently came across a code sample in the book You Don't Know JS: Scope & Closures that is puzzling to me. "Function declarations that appear inside of normal blocks typically hoist to the enclosing scope, rather than being conditional as this ...

What is the best way to use res.sendFile() to serve a file from a separate directory in an Express.js web application?

I have a situation within the controllers folder: //controler.js exports.serve_sitemap = (req, res) => { res.sendFile("../../sitemap.xml"); // or // res.send(__dirname + "./sitemap.xml") // But both options are not working }; ...

Error: Unable to execute candidate.toLowerCase as a function

Encountering the following errors: `Uncaught TypeError: candidate.toLowerCase is not a function. I am utilizing the AutoComplete API within Material UI, however, when I search in the input field, it leads me to a blank page. https://i.sstatic.net/Yv3ZU.pn ...

Storing Code into mongoDB with the Help of CasperJS

What is the best way to save data scraped using casperjs into MongoDB? My casperjs script scrapes information from millions of websites and saves each site's content in its own folder. However, I have come to realize that it would be more efficient to ...

Delivering real-time updates from a .NET API to VueJS through push notifications

Currently, this is just a theoretical description as I haven't written any code yet. I was hoping to brainstorm ideas with others. Imagine I have a VueJS application, like a To-Do app for example. It displays all the tasks I need to complete on a giv ...

Preserving client-side page state during page reloads in angular.js apps

I am currently developing a Single Page application using angular.js and I have encountered an issue that I am struggling to resolve. When performing a full page refresh in an angular app, how can we verify if the user still has a valid session? While Sta ...

When submitting the club form, my goal is to automatically generate a club admin within the user list in activeadmin

My dashboard.rb setup looks like this: ActiveAdmin.register_page "Dashboard" do menu priority: 1, label: proc{ I18n.t("active_admin.dashboard") } content title: proc{ I18n.t("active_admin.dashboard") } do # form render 'form' # Thi ...

Ways to add AJAX information to select2

I am currently utilizing a select2 dropdown feature and I am attempting to configure it in such a way that it dynamically displays the leads based on the JSON response. As you can observe in the image provided below, the text correctly yields a JSON array ...

"Encountered an error while trying to locate the view" in a simple Express.js application

Embarking on the journey to learn Express.js, I decided to create a simple Express app. The structure of my app.js is as follows: var express = require('express'); var app = express(); app.configure(function(){ app.set('view engine&ap ...

When a cookie is set in NextJS with a static export, it reverts back to its original

My current project involves building a multilingual website. To handle language selection, I have implemented a system where the chosen language is stored in a cookie and retrieved using getInitialProps in the _app file, which is then passed as a context A ...

A guide on extracting information from a personal Flask JSON route endpoint with Axios

I am looking to store JSON data in a variable using Axios in Javascript. The JSON endpoint is generated by my own server's route http://123.4.5.6:7890/json. I have been successful with this function: async function getClasses() { const res = await ...

Looking for a node.js IDE on OS X that can display JSON objects similar to how they appear in the console of Chrome or Firefox?

While using Google Chrome, I noticed that when I console.log(object), a detailed view of the object is displayed in the console instead of just a string representation. This feature is incredibly useful. Unfortunately, when running node.js scripts on my ...

Updating reactive objects in Vue.js 3 while maintaining reactivity without any loss

I'm looking for the best approach to update a reactive object with data after fetching it: setup(){ const formData = reactive({}) onMounted(() => { fetchData().then((data) => { if (data) { formData = data //is ...

A guide on navigating to a different component in Vuejs using a link

<div class="enterprise-details" style="margin-top: 20px"> Already signed up? <a href="#"> LOGIN</a></div> <!-- Component for redirection --> <b-button v-if="!registeredUser" class="button-self" v-b-modal.modal-x>Lo ...

What could be causing the inability to 'GET' a page on an express app?

As a beginner in web app development, I've been self-teaching Node Express. While I've had success running simple express apps on Cloud9 environments, I'm facing difficulties getting them to work with VS Code. The server starts up fine, but ...

How can I display components using Angular CLI 5 without any visual output?

The index.html page is not displaying anything, not even the "App works" message that should appear in a basic initial project ng --version Angular CLI: 1.6.0 Node: 8.9.1 OS: darwin x64 Angular: 5.1.0 ... animations, common, compiler, compiler-cli, core, ...

Updating a dataview inside a Panel in extjs 3.4

I am facing an issue with my extjs Panel component that includes a dataview item. Initially, it works perfectly fine in displaying images from a store. However, upon reloading the imgStore with new image URLs (triggered by a user search for a different cit ...

Making AngularJS 'PUT' requests: The process of submitting only the data in a form

I am facing an issue while updating user data in Angular. When I send a 'PUT' request, the entire user $scope is being sent instead of only the fields visible on the form. To retrieve and update the data, I am using a Factory. Below is my edit f ...