Tips for generating dynamic JSON: Organize the data by filtering it and creating key-value pairs for the appropriate JSON objects

How can I generate dynamic JSON based on input, filter data, and create appropriate key-value pairs for JSON objects?
The database schema can be viewed https://i.sstatic.net/iP1JS.png

Although I attempted the following code, it did not produce the desired result...

success: function (data) {
    //Calculate length
    data.value.length;
    
    empData = '[';
    $.each(data.value, function (index, item) {
        var dataLen = data.value.length;

        empData += `{`;

        if (item.STATUS == 'Active') {

            if (item.NODE == 'Testing') {
                empData += `"DDM_CO2" : {
                        "DESIGNATION": "${item.DESIGNATION}",
                        "EMPLOYMENT": "${item.EMPLOYMENT}",                     
                        "GENDER": "${item.GENDER}",                     
                        "Name1": "${item.Name1}",
                        "ROLE": "${item.ROLE}"                    
                    },`;
            } else if (item.NODE == 'Devlopment') {
                empData += `"GPH" : {
                        "DESIGNATION": "${item.DESIGNATION}",
                        "EMPLOYMENT": "${item.EMPLOYMENT}",                     
                        "GENDER": "${item.GENDER}",                     
                        "Name1": "${item.Name1}",
                        "ROLE": "${item.ROLE}"
                    }`;
            }
        }
    });
    empData += ']';
    empData = JSON.parse(empData);
    console.log(empData);

},

Answer №1

Here is an example of a working code snippet

function processData(data) {
    //initialize an array to store employee objects
    var empData = [];
    $.each(data.value, function(index, item) {

        if (item.STATUS == 'Active') {
            if (item.NODE == 'Testing') {
                //create custom object for DDM_CO2 node
                var emp = {
                    DDM_CO2: {
                        DESIGNATION: item.DESIGNATION,
                        EMPLOYMENT: item.EMPLOYMENT
                        //etc: item.etc
                        //etc: item.etc
                        //etc: item.etc
                    }
                };
                //add the object to the array
                empData.push(emp);
            } else if (item.NODE == 'Development') {
                //create custom object for GPH node
                var emp = {
                    GPH: {
                        DESIGNATION: item.DESIGNATION,
                        EMPLOYMENT: item.EMPLOYMENT,
                        GENDER: item.GENDER,
                        Name1: item.Name1,
                        ROLE: item.ROLE
                    }
                };
                empData.push(emp);
            }
        }
    });
}

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

Using event.target to pass HTML form data to FormData is causing an error stating that the Argument of type 'EventTarget' cannot be assigned to a parameter of type 'HTMLFormElement'

Looking to extract data from a form and store it in FormData: const handleSubmit = (e: FormEvent<HTMLFormElement>) => { e.preventDefault(); const formData = new FormData(e.target as HTMLFormElement); const value = formData.get(' ...

Group Hover by StyleX

I recently experimented with the innovative StyleX library and encountered a particular challenge. Can a group hover effect be achieved for a component solely using this library? For instance, let's assume we have the following component in Tailwind ...

Error on Laravel 7: Unable to retrieve resource - the server returned a 400 (Bad Request) status code

Seeking assistance with a technical issue involving Razorpay. I'm encountering difficulty passing a value from the controller to JavaScript in the view. The data-order_id field is not populating, resulting in the error mentioned above, indicating a nu ...

Error: The property 'rtl' is not defined and cannot be read

I'm currently in the process of developing a vuejs component library that utilizes vuetify 2.1.4 and attempting to import it into another application locally through npm link. However, I'm encountering numerous errors such as TypeError: Cannot ...

`Creating the perfect bar``

Currently working on my resume using Angular and I am interested in incorporating a visual representation of my skill level in specific subjects. Came across something that caught my eye here: https://i.sstatic.net/84cir.png The challenge now is figuring ...

How can I locate and substitute a specific script line in the header using Jquery?

I need to update an outdated version of JQuery that I have no control over, as it's managed externally through a CMS and I can't make changes to it. But I want to switch to a newer version of JQuery. Here is the old code: <script type="text/ ...

Unable to apply CSS styles to a form input using Ajax

Alright, so I've got this Ajax form that successfully fetches the data and displays it in #register_msg. However, I'm also trying to apply some styles to the input forms. Here's my Ajax code, along with the form. But for some reason, the st ...

Encountering difficulty extracting information from an XML document within the Parse Cloud utilizing the XMLReader in an Express application

My goal is to extract elements from an XML file that I have already stored on the Parse Cloud for my Express app. I began coding after finding a helpful resource on using XMLReader with XPath on cloud code, as well as a guide on Parse httpRequest for retri ...

Creating a Build System for JavaScript in Sublime Text

While working on developing an application using node.js, I decided to create a JavaScript build system in Sublime Text 3 on my Ubuntu OS. I made a new build system file named nodey.sublime-build with the following contents: { "cmd": ["node","$file"," ...

The app is having trouble loading in Node because it is unable to recognize jQuery

I am currently using Node to debug a JavaScript file that includes some JQuery. However, when I load the files, the $ sign is not recognized. I have installed JQuery locally using the command npm install jquery -save-dev. The result of "npm jquery -versio ...

What is the best way to limit the length of text in a div if it surpasses a

As I work on a website, users have the ability to add headings to different sections of a page. For example: M11-001 - loss of container and goods from Manchester Some headings can be quite detailed, but in reality, only the first few words are needed to ...

When using AngularJS in conjunction with Karma-Jasmine, it is important to note that the functions verifyNoOutstandingExpectation() and verifyNoOutstandingRequest() may not

There is an unresolved HTTP request that needs to be flushed. When I use the following code afterEach(function(){ $httpBackend.verifyNoOutstandingExpectation(); $httpBackend.verifyNoOutstandingRequest(); }); The code functions correctly and I ...

A guide on integrating MySQL table data into React card elements

After successfully populating a React table within a card (see first code snippet below) with MySQL table data, I am now faced with the challenge of populating a card's information with the same SQL data. The image below displays how cards are curren ...

Steps for removing an element from an array using Mongoose and Node.js

After reading and attempting to implement the solutions provided by others, I am still struggling to understand why it's not working for me. This is my first project involving backend development. While progressing through a course, I decided to work ...

Is there a more efficient method for handling this JSON dataset?

After delving into Sitepoint's "Novice to Ninja" and starting to explore jQuery, I can't help but question if there is a more efficient way to write the code I've put together. The resounding answer appears to be "yes." All these cumbersome ...

What is the process for loading a script file from within a component's HTML?

My goal was to include a specific script file in the component html, but I noticed that when I added the script reference within the html itself, the inner script file was not rendered along with the component on the page. Component import { Component } ...

Are there alternative methods for handling routes in React, other than using the react-router-dom@latest library?

Currently, I am focused on a frontend project. One of the tasks at hand is to configure the network of routes. During my research, I came across react-router-dom@latest as a potential solution. However, I am curious to explore alternative options availa ...

Error encountered: Javascript throws an error while trying to initialize the Bootstrap datetimepicker if the input value only

My requirement is to utilize the DateTime Picker plugin and load only the Time picker component. To achieve this functionality, I have initialized my input field in the following manner, allowing only time selection: jsfiddle: <div class="input-group ...

What is the best way to incorporate "thread.sleep" in an Angular 7 app within a non-async method like ngOnInit()?

Despite the numerous questions and solutions available on Stack Overflow, none of them seem to work when called from a component's init function that is not asynchronous. Here's an example: private delay(ms: number) { return new Promise( ...

How can I set the textbox focus to the end of the text after a postback?

In my ASP.Net form, there is a text box and a button. When the user clicks the button, it adds text to an ASP:TextBox during a postback (it adds a specific "starter text"). After the postback, I want the focus to be set to the end of the text in the textbo ...