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

Modify a property within an object stored in an array using React with Redux

When trying to dispatch an action that updates values in the redux state by passing an array, I encountered an issue. It seems that despite attempting to update the array by changing object values, I kept facing this error - "Cannot assign to read only pro ...

Is there a way to transform a List of ViewHolder objects into JSON format and then transmit it to a server using a POST request?

I need to send a List of ViewHolder data to the server using JSON with a POST request. Here is an example of my code: private List<ViewHolder> pizza = new ArrayList<ViewHolder>(); pizza.add(new ViewHolder("7", "Наполеон" ...

One or multiple web browsers set in the Browserslist of the project

I have recently started working with the Ionic framework and encountered some warnings while setting up my application. Can anyone help me with a solution? [ng] When starting the Ionic application, I received the following warnings: [ng] One or more browse ...

What exactly are Node.js core files?

I recently set up my Node.js application directory and noticed a presence of several core.* files. I am curious about their purpose - can these files be safely removed? The setup involves installing Node.js alongside Apache using mod_proxy to host one of ...

The data from the server is inaccessible to node.js

I am a beginner in nodejs and jquery, trying to retrieve data from a server and use it to update a webpage: Using jquery on the client side: I would like to change the text inside '#info' element with the data fetched from the server. $('# ...

Tips for implementing daterangepicker js in an Angular 2 project

I'm currently working on an Angular 2 project and I'm looking to integrate the daterangepicker.js library for a date range picker. If you're not familiar with it, you can find more information about the library here. Here's the HTML co ...

How to toggle hidden links with AngularJS or vanilla JavaScript with a click事件

When the "Show all" button is clicked, I would like to display all elements. If the "1st half" link is clicked, I want to show "abc", "def", and "ghi". When the 2nd link "2nd half" is clicked, I want to display "jkl", "mno", and "pqr". Then, when the "show ...

Ways to resolve the issue of BrowserWindow not being recognized as a constructor when trying to create a child window within the Electron

Currently, I am utilizing electron to construct an application with two windows. In my attempt to open a second window from the renderer process, I have implemented the following code snippet: const electron = require('electron'); const BrowserW ...

Transform JSON dictionary into a row within a Pandas DataFrame

I have retrieved JSON data from a URL, resulting in a dictionary. How can I restructure this dictionary so that each key becomes a column and the timestamp acts as the row index for each entry gathered from the URL? Below is the raw data obtained: with u ...

Using jQuery to send JSON data through AJAX to PHP

I'm attempting to utilize jQuery AJAX to send JSON data to a PHP file. My goal is to extract the values and IDs from multiple child elements, create a JSON object with this data, and then transmit that object to a PHP file for processing and insertion ...

Tips for replacing div content using $.ajax similar to $.postWould you like to learn how

The Challenge: I need assistance in converting my existing code from using $.post to utilizing $.ajax for better synchronization and displaying a message until the request is completed. I am particularly interested in learning how I can achieve this usin ...

Working with JSON data in Java and displaying it in a user interface

As a newcomer to JAVA, I find myself facing JSON data for the first time. My task is to develop a news desktop application by sending a GET request to a web address that returns JSON output, as illustrated below. ****JSON OUTPUT**** { "status": ...

What could be preventing me from successfully calling the JavaScript AJAX function in this particular situation?

Here is my code snippet from a smarty template: <form name="transaction_form" id="transaction_form"> <table class="trnsction_details" width="100%" cellpadding="5" > <tbody> <tr> ...

The appropriate method for showcasing cards within lists, such as in the platform Trello

I'm in the process of developing a project similar to Trello, but I'm facing some challenges on how to proceed. Initially, I created an 'init' function within my AngularJS Controller to handle HTTP requests: $scope.loadLists(); ...

Converting JSON Object into C# class following an API request

When I receive a JSON object from an API call, I am struggling to translate it into a C# class that I can effectively iterate over. The issue lies in the inconsistency of the JSON structure, especially under the 'data' section where the object na ...

Learn the process of crafting a SELECT query in MySQL for JSON array data

I have been attempting to extract the email from this JSON array, but it keeps returning a null value. [ { "name": "Arun", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="422330372c022330372c6c212 ...

Tips for wrapping a function call that may occasionally involve asynchronous behavior to ensure it runs synchronously

I am dealing with a function that functions as follows: _setDataChunk: function (action) { var self = this; /* some code */ var data = self._getDataChunk(action); populateWidget(data); } Sometimes GetDataChunk cont ...

Vue application experiencing never-ending update cycle following array assignment

Here is the JavaScript code I am working with: const storage = new Vue({ el: '#full-table', delimiters: ['[[', ']]'], data: { events: [], counter: 0, }, methods: { eventCounter: fu ...

Easy steps to automatically disable a checkbox once the expiration date has been reached

I have this PHP code that retrieves values from my database. I want to prevent users from selecting or modifying items with expired dates. Could you assist me with this? The code below currently displays 'Expired' and 'Not Expired' on ...

The outline color cannot be removed from vue-carousel

I recently downloaded the Vue Carousel library and here is the version I am using: "vue": "^2.6.11", "vue-carousel": "^0.18.0", When I click on the pagination, a focus effect is added to the element with an outlin ...