Rebuilding JSON data with stringify manipulation

I have a database with various cells and values stored under each cell.

The cells in the database are: id, name, duration, date, and relationid.

This is the code I am currently using:

var result = {} 
properties.data.forEach(addToResult); //Retrieves data from the database using properties.data
    
instance.data.datavarb = JSON.stringify(result); //Sends the converted data as JSON
      
function addToResult(pair,isjson){ //Operations
if(isjson===true) result[pair.key] = JSON.parse(pair.value); else result[pair.key] = pair.value;
}

I am encountering two issues:

1- First issue: This is how I retrieve the value after converting to JSON:

{"id":"1","name":"Football","duration":"12","date":"02-07-2018","relationid":null}

Desired format:

{id:1, name:"Football", duration:12, date:"02-07-2018", relationid:null}

I need to remove the quotes (""), specifically from the numbers (id, duration, and relationid) and their corresponding values.

2- Second issue: In the first problem, I only demonstrated one of the three values parsed from my database. What happens when I parse all three? Here is how it appears:

{"id":"1, 2, 3","name":"Football, France, Belgium","duration":"12, 4, 3","date":"02-07-2018, 08-07-2018, 10-07-2018","relationid":", 1, 1"}

Instead of creating individual entries for each set of values, it combines them into the same identifiers (id, name, duration). For my purpose, I require the following structure:

{id:1, name:"Football", duration:12, date:"02-07-2018", relationid:null},
{id:2, name:"France", duration:4, date:"08-07-2018", relationid:1},
{id:3, name:"Belgium", duration:3, date:"10-07-2018", relationid:1}

Thank you very much!!

Answer №1

To determine if the values resemble integers, you can run a test and then parse them.

function updateResult(pair,isJson){ //performing calculations
    if(isJson===true) {
        result[pair.key] = JSON.parse(pair.value); 
    } else if (/^\d+$/.test(pair.value)) {
        result[pair.key] = Number(pair.value);
    } else {
        result[pair.key] = pair.value;
    }
}

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

Is it possible to make changes to local storage data without impacting the rest of the data set?

https://i.sstatic.net/BBcJF.pngI am looking for a way to modify specific data in the local storage without affecting any other stored information. However, I have encountered an issue where editing values works correctly for the first three attempts, but ...

"Exploring the power of Knockout JS by utilizing the foreach loop to iterate through

I have an observableArray: self.stats = ko.observableArray([ {"DFTD" : new Stat("Defensive TD", "DFTD",0,20,0,self.playerGroups[1])}, {"GL" : new Stat("Games Lost", "GL",0,16,0,self.playerGroups[2])}, {"FGA" : new Stat("Field Go ...

MongoDB Integration of Collections - No Data Population

Having trouble merging a client and an account collection. When I use res.send(client), only the account id's are returned. Unsure how to include account information in clients. Have seen one to many solutions, but struggling with this two-way relati ...

Updating React state for no apparent reason

My issue is quite straightforward. In my application, I have a user list stored in the state which is populated by a database call. Additionally, there is a selected user that gets filled when an element in the user list is clicked. Whenever a userlist e ...

Utilize a custom attribute in Bootstrap 4 tooltips instead of the standard "title" attribute to define the text displayed in

For my application, I'm utilizing Bootstrap 4 along with tooltips. My objective is to toggle the tooltips individually and only display them upon clicking. The following code allows me to achieve this: <input type="text" id="name" class="form-cont ...

What is the method for rendering an ejs template from express using fetch without the need to submit a form?

login.js file: const form = document.getElementById('loginForm'); form.addEventListener('submit',async(e)=>{ e.preventDefault(); return await fetch(`localhost:8000/route`, { method: "get", heade ...

Unable to retrieve the REST API from the domain class with a composite key in Grails

I've been encountering an issue with my Grails domain class that connects to an Oracle DB and has a composite primary key. Whenever I attempt to render the list by hitting the /gender endpoint, I consistently receive this error message. I've been ...

Retrieving and showcasing data points from a JSON array within a Select Statement in Postgres

I'm currently working on developing code to retrieve values directly from a text field that contains JSON within a JSON array. My goal is to display these values along with an ID using Row_Number, but I'm facing some challenges. Additionally, I ...

Tips on destructuring an object property from a Pinia getter that may return an object based on a condition

I obtained this particular Store: export const useMyStore = defineStore('myStore', { state: () => { return { openTransOnly: false, keyword: '', openTransStatus: { nextPage: 0, complete: false }, pastDueT ...

Ensure that the view is only updated once the JSON has been completely received from the AJAX call in AngularJS

Just starting out with angularJS and still in the learning phase. I'm currently working on creating a navbar for the header that will fetch data from an ajax call. The issue I'm facing is that it displays {{obj.pageData}} until the data is fully ...

Tips for utilizing the npm jQuery module effectively

What is the best way to import jquery into multiple modules in node? Should I make it a global variable, or should I use require('jquery') in each module that needs it? I encountered an error while attempting to utilize the package. TypeError: ...

The Art of Receiving Feedback in THREE.js

I have created a feedback loop using backbuffer in my code with the following implementation: function render() { renderer.setRenderTarget(BufferA); renderer.render(BufferAScene, camera); renderer.setRenderTarget(null); rendere ...

Using JavaScript's if-else statements is akin to a checkbox that is always in its

When working with checkboxes, I can retrieve the state (checked or unchecked) in the browser developer console using $("#blackbox").prop('checked')or $('#blackbox').is(':checked'). I have tried both methods. For example, if I ...

Tips for avoiding an automatic slide up in a CSS menu

Is there a way to disable the automatic slide-up effect on my CSS menu when clicking a list item? I have tried using stop().slideup() function in my JavaScript code, but it doesn't seem to work. Additionally, I would like to highlight the selected lis ...

Steps to activate internet access on the Samsung Gear S2

When I press a toggle on a web application for the gear s2 (javascript), I send out an http request: ( function () { var led001Button = document.getElementById("Led001"), led002Button = document.getElementById("Led002"); function http ...

Learn how to generate a JSON data table for Google Charts with data from MySQL using a custom PHP function. Check out a fully functional example to see how it all works. Is

I recently completed a personal project involving PHP and MySQL, where I fetched data from the database, encoded it to JSON format (including column information), and then visualized it using Google Data Table with Ajax. The project was successful, but I ...

Comparison of memory allocation efficiency with loop iteration

Within my C program, I have developed a function that accepts a Unicode codepoint as a wide character and then returns a pointer to an array of unsigned characters representing the UTF8 format of that wide character. Additionally, another function in my pr ...

Using the global value in a Javascript replace() function causes ng-bind-html to malfunction

When trying to utilize ng-bind-html alongside JavaScript's replace() function, everything works smoothly without using a global value in the replace(). However, as soon as I add something like replace(/test/g, 'TEST'), an error appears in th ...

Angular does not wait for the backend service call response in tap

Does anyone have a solution for subscribing to responses when the tap operator is used in a service? edit(status) { dataObj.val = status; // call post service with status.. this.service .update(dataObj) .pipe(takeUntil(this._n ...

What is the best way to transform a BLOB Buffer into a Base64 string using Swift?

I am facing an issue where I have stored a base64 string as a BLOB in Swift, but now I am struggling to figure out how to convert the buffered blob back into a UIImage. When storing it, Blob converts it into buffer, here is what I did: let image: UII ...