Converting an Array with Key-Value pairs to a JSON object using JavaScript

After using JSON.stringify() on an array in JavaScript, the resulting data appears as follows:

[  
   {  
      "typeOfLoan":"Home"
   },
   {  
      "typeOfResidency":"Primary"
   },
   {  
      "downPayment":"5%"
   },
   {  
      "stage":"Just Looking"
   },
   {  
      "firstName":"Jared"
   },
   {  
      "lastName":"Example"
   },
   {  
      "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9dd7fceff8f9ddf9f8f0f2b3fef2f0">[email protected]</a>"
   },
   {  
      "cell":"8888888888"
   },
   {  
      "loanofficer":"Jim Loan"
   }
]

I need to convert this structure into a standard JSON object for POST submission. Despite researching various solutions and attempting them all, I am still encountering syntax errors that I cannot resolve. The array is stored in the variable jsonArray.

Answer №1

The group of objects, each with a single key, appears suspicious. It may be more efficient to consolidate all keys into a single object literal before sending it to the backend (and parsing it there). To do this, combine the multiple objects into one and then execute your ajax request to POST it wherever needed. Below is a method to achieve this:

let arr = [{"typeOfLoan":"Home"},{"typeOfResidency":"Primary"},{"downPayment":"5%"},{"stage":"Just Looking"},{"firstName":"Jared"},{"lastName":"Example"},{"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4f052e3d2a2b0f2b2a2220612c2022">[email protected]</a>"},{"cell":"8888888888"},{"loanofficer":"Jim Loan"}];

let res = arr.reduce((a,b) => {
  let key = Object.keys(b)[0];
  a[key] = b[key];
  return a;
}, {});

console.log(res);

Depending on the method you use to send it to the backend, you might need to apply JSON.stringify to res

Answer №2

Prior to converting it into a string, ensure that your request payload is transformed from an array into an object.

const data = [{"loanType":"Vehicle"},{"residencyType":"Rental"},{"deposit":"10%"},{"status":"Researching"},{"firstName":"Sara"},{"lastName":"Smith"},{"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="356f44677677954647494b4a0b464a48">[email protected]</a>"},{"phone":"9999999999"},{"agent":"Kate Smith"}];

const requestData = data.reduce(function(mergedData, currentItem){
  return Object.assign(mergedData, currentItem);
}, {});

console.log(requestData);

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

What is the best approach for identifying the anticipated table row when transforming JSON data into a datatable?

Is there a way to determine the expected datatable row without directly converting JSON data into a datatable? ...

Every character entered in JSP should trigger an instant retrieval of the corresponding string in the servlet

Having a JSP file that contains a text field: <form action="someServlet" method=post> <input type ="text" name="user" id="uname"> <button type="submit" id="submit">Submit</button> </form> When typing each letter in the JSP, ...

Is it possible to achieve this using an alternate method such as CSS?

Currently, I am working on a function that will apply shadow effects to all buttons within a specific class when hovered over. However, due to the dynamic nature of the buttons created based on the data retrieved from the database, assigning individual IDs ...

How to efficiently eliminate multiple entries with SREM in ioredis?

I am curious about the proper syntax for removing multiple entries using the SREM command. When I try this: const myKey = "myKey"; const entriesToRemove: string[] = ... this.redisClient.srem(myKey, entriesToRemove); I end up with: ReplyError: ...

Is it possible to retrieve a JSON response by making a jQuery.ajax request to an appengine URL?

Attempting to retrieve response data via ajax from the following URL: http://recipesid.appspot.com/api.user?method=user.query&[email protected] Encountering issues when trying to run the code. Please assist in resolving this problem. $.ajax({ ...

What is the best way to relocate a child component to a different parent in React?

I have a list of child components with checkboxes, and when a checkbox is clicked, I want to move that child component inside another div. Below is an illustration of how my app should look. I need to select student names and shift them up under the "Pres ...

Failure to trigger jQuery.ajax success function on Windows XP operating system

Snippet: $.ajax({ type: "POST", url: "students/login", data:{"data[Student][email]":_email,"data[Student][password]":_password}, beforeSend: function(){ $("#confirm").text(""); }, error: function (xhr, status) { ale ...

Transform JSON into a JavaScript array object using node.js

My knowledge of Javascript is limited and I need assistance with a .json file that has the following structure: { "results": [ { "challenger": { "__type": "Pointer", "className": "Player", "objectId": "STWAxAHKay" }, "c ...

Mastering the art of knowing when to implement asynchronous and synchronous programming techniques is essential for

As I explore asynchronous programming in JavaScript, I am faced with the challenge of integrating two email providers: Sendgrid and Mailgun. My goal is to send an email using one provider, and if any errors occur during the process, automatically resend th ...

Unable to load routes from ./app.js in the file ./src/routes/index.js

Just dipping my toes into the world of nodejs. I recently moved all my routes from app.js to a separate file located at PROJECT_DIR/src/routes/index.js. However, when I try to open the page in my browser, it displays "Cannot GET /wines". Below are snippets ...

JavaScript code encounters difficulties parsing HTML source

I'm attempting to reconstruct the WhateverOrigin service, which can be found at this link: Nevertheless, when I try running it in my web browser, this code that functioned perfectly with WhateverOrigin no longer functions properly with my imitation s ...

Tips for preventing the playback of the sound while recording

When creating a basic JavaScript application that involves opening a stream from the user and analyzing frequencies, I found that while Google Chrome and Opera work well by providing feedback in the headphones, Firefox often remains silent. Additionally, F ...

Thorax.js bower installation issue

After following the instructions in this guide: https://github.com/walmartlabs/thorax-seed/blob/master/README.md, I ran into an unexpected issue on my Windows machine. When running npm start It seems like bower is doing a lot of work (presumably loading ...

The event listener attached to this model is failing to trigger when there are

The issue is that the "change" event is not being triggered in the code snippet below. var PageView = Backbone.View.extend({ el: $("body"), initialize: function(){ this.model.on("change:loading", this.loader, this); }, loader: func ...

What could be causing the value of response.name to be undefined in this situation?

Despite extensively searching through various StackOverflow threads, none of the suggested solutions seemed to work for my specific scenario. Upon analyzing the response using console.log(response), I received an "Object Object" message. I am puzzled as to ...

Invoke the parent method within the child application

I have a checkbox on the child app controller. When the user clicks it, I need to call a method from the parent controller: Parent app controller: <div ng-controller="ParentCntr as parentCntr"> <child-app></child-app> </div> C ...

Tips for closing a popup without exiting the entire webpage

I'm facing an issue while trying to create a video playlist using two HTML files (index.html and video.html). In my video.html file, I have set up a popup for playing videos. However, whenever I close the popup or click anywhere on the page, it redire ...

Guide to integrating a deterministic game loop with tick-based mechanics

My current project involves creating a "simple" 3D game using Three.js and incorporating a network framework for multiplayer functionality in the future. After some research, I found that many "action" games utilize a "tick" based game loop to sync clients ...

Minimize the number of clicks needed to navigate using the HTML/JavaScript navigation

On my website, I have a navigation bar that changes the contents of a div when a user clicks on an item. However, if the user clicks multiple times in quick succession, the content changes too many times. I want to ensure that the content only changes once ...

What could be the reason for the 'tsc' command not functioning in the Git Bash terminal but working perfectly in the command prompt?

I recently installed TypeScript globally on my machine, but I am facing an issue while trying to use it in the git bash terminal. Whenever I run tsc -v, I encounter the following error: C:\Users\itupe\AppData\Roaming\npm/node: l ...