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

typescript - transforming text into numerical values

newbalance = (Number(this.balance)) + (Number(this.pastAmount)); The result for my newbalance calculation is coming back as undefined, even though this.balance is 34 and this.pastAmount is 23. I've set this up in the controller and I'm trying t ...

Instead of using a v-if condition, add a condition directly in the Vue attribute

Apologies for the unclear title, as I am unsure of what to name it with regards to my current issue, I am attempting to create a component layout using vuetify grid. I have a clear idea of how to do this conventionally, like so: <template> <v-fl ...

The PUT rest service does not function in AngularJS version 1.0.8

I am facing an issue with my AngularJS application that has a CRUD Rest service. While the Create, Read, and Delete methods are functioning properly, the PUT method is not working. I have searched on Stackoverflow and found similar problems with accepted s ...

AngularJS is not showing the dropdown options as expected

I am facing an issue where the dropdown list options are not displaying, even though I am able to fetch the data in the controller but not in HTML. Here is the code snippet: In HTML <select name="nameSelect" id="nameSelect" ng-model="model.name"> ...

Problems Arising with Javascript Animation Functionality

I've created a script for an interactive "reel" that moves up or down when clicking on specific arrow buttons. However, I'm encountering two issues: 1) The up arrow causes it to move downward, while the down arrow moves it upward. 2) After exe ...

The issue with executing event.keyCode == 13 in Firefox remains unresolved

I've implemented a function that sends comments only when the "enter" key is pressed, but not when it's combined with the "shift" key: $(msg).keypress(function (e) { if (event.keyCode == 13 && event.shiftKey) { event.stopProp ...

I recently started delving into React Native and am currently exploring how to implement custom fonts in my application. However, I have encountered an error that is preventing me from successfully integrating

The Issue: The error I encountered only appeared after including font-related code (such as importing from "expo-font" and using "AppLoading" from "expo", and utilizing the "Font.loadAsync()" function). Error: Element type is invalid: expected a string (fo ...

Could someone clarify the specific workings of the Google V8 bytecode related to the creation of object literals

Check out this awesome piece of JavaScript code! const person = { name: 'John', age: 30 }; console.log(person); Here's the Google V8 byte code generated by using node js option --print-bytecode. [generated bytecode for function:] ...

Leveraging kazupon/vue-i18n within a Vuex module

Utilizing the Vue-i18n Library for Localization The functions Vue.t() || $t() || trans() expect a string as a key to be translated by vue-i18n Hello everyone! I'm currently experimenting with the code below: import Vue from 'vue' expor ...

Accessing variables from an external script in jsdom

Here is a simple example of jsdom code using the script parameter. Despite my best efforts to reference external JS files, I keep running into this issue: ReferenceError: exVar is not defined Does anyone know what might be causing this problem and how ...

Incrementing values in ng-repeat object automatically

My project involves extracting game information from mlb.com and utilizing angularjs along with the ng-repeat directive to display it. A sample of the JSON feed is shown below. { "data": { "games": { "next_day_date": "2017-08-19", "mo ...

Generate a form using code that has the trigger turned off by default

Summary: Looking for a solution to avoid the automatic disabling of a programmatically created trigger in a form. function autoTrigger(e) { var result = {}; var responses = e.response.getItemResponses(); for (var i = 0; i < responses.length; i++) ...

Develop a nodejs script to make a request using a curl or similar method

Can anyone help me figure out how to replicate the functionality of this OpenSSL command using Node.js or curl? The command is: openssl s_client api-prd.koerich.com.br:443 2> / dev / null | openssl x509 -noout -dates. I have been unsuccessful in my at ...

Rails: Utilizing AJAX to dynamically populate Bootstrap dropdown menus

In the setup I have, there is a dropdown responsible for displaying notifications. <li class="notifications dropdown"> <a class="dropdown-toggle" id="dLabel" role="button" data-remote="true" data-toggle="dropdown" data-target="#" href="/notifi ...

What is the best way to transform a JSON object with various key-value pairs into a list using JavaScript?

There's a JSON string that I need to convert into a different format, here is the original: var jsonData = [{"label":"Hass1(<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="354d4d4d6a465058755d5a4158545c591b565a58">[emai ...

Click to Rotate the Shape

I am attempting to apply a rotation effect on a shape when clicked using jQuery and CSS. My goal is to select the element with the id of x and toggle the class rotate on and off. The rotate class utilizes the CSS transform property to achieve the desired r ...

Execute with jQuery using Multiple Attribute Selector

I am attempting to input numeric values using a keyboard. My issue is as follows: the keyboard has an "Accept" button, and I have multiple text fields. I want to assign a different action for each text field. I attempted to use multiple attribute selector ...

Taking a Breather with mywindow.print()

I'm currently utilizing a fantastic printing script that I found: <script type="text/javascript"> function PrintElem(elem) { Popup($(elem).text()); } function Popup(data) { var mywindow = window.ope ...

Issues with FUNCTION_INVOCATION_FAILED error encountered during deployment on Vercel and Nuxt

Just imported a Nuxt project from GitHub that includes the vercel.json config: { "version": 2, "builds": [ { "src": "nuxt.config.js", "use": "@nuxtjs/vercel-builder" ...

Oh no! It seems like the build script is missing in the NPM

https://i.stack.imgur.com/el7zM.jpg npm ERR! missing script: build; I find it strange, what could be causing this issue? Any suggestions? I have included the fullstack error with the package.json. Please also review the build.sh code below. Fullstack err ...