Is there a way to transform this JSON string into a particular format?

When moving a string from view to controller, I have encountered an issue. Below is the ajax code I am using:

    var formData = $('#spec-wip-form, #platingspec-form').serializeArray();
    var platingId = @Model.PlatingId;

    var form = JSON.stringify(formData);
    $.ajax({
        url: "/Specifications/Edit",
        type: 'PUT',
        data: { form, cleaningProcess, platingId },
        success: function () {
            onUpdated();
        }
    });

The current JSON format generated by this code looks like this:

"[{\"name\":\"PlatingId\",\"value\":\"1\"},{\"name\":\"DivisionId\",\"value\":\"79\"}]

I wish for the format to be as follows:

"[{\"PlatingId\":\"1\"},{\"DivisionId\":\"79\"}]

My initial attempt to solve this involved using the following code section:

var formData = $('#spec-wip-form, #platingspec-form').serialize();

However, this resulted in the following output:

formData: PlatingId=1&DivisionId=79&

Any suggestions on how I can achieve the desired JSON format?

Answer №1

Big thanks to @SebastionSimon for the helpful revision. By the way, this code is not redundantly stringified twice in order to match your anticipated output. If needed, you have the option to utilize JSON.stringify a second time for consistency.

let jsonData = '[{"name":"PlatingId","value":"1"},{"name":"DivisionId","value":"79"}]';

let newJsonData = JSON.stringify(
    JSON.parse(jsonData).map(
        ({name, value}) => ({[name]: value})
        ))

console.log(newJsonData)

Answer №2

Utilize the Object.fromEntries() method to consolidate multiple key-value pairs into a single object.

const formData = [{"name":"UserID","value":"123"},{"name":"Role","value":"Admin"}];

const newObj = Object.fromEntries(formData.map(({name,value})=> [name, value]));

console.log(newObj)

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

Issues with sending emails through Nodemailer in a Next.js project using Typescript

I'm currently working on a personal project using Nodemailer along with Next.js and Typescript. This is my first time incorporating Nodemailer into my project, and I've encountered some issues while trying to make it work. I've been followin ...

Why is the Javascript code outputting undefined and NaN during execution?

As a newcomer to the world of javascript, I am venturing into learning its fundamental concepts. In my quest for knowledge, I've dabbled in file reading and came up with a small script which you can find below. // Incorporating the fs (filesystem) mo ...

Performing an AJAX request within another AJAX request using jQuery

$.ajax({ type: 'POST', url: searchpage, dataType: "json", data: { id: id }, success: function(data) { var id1 = []; for(var i = 0; i < data.length; i++){ id1 .push({ ...

Choose specific dates from the data pickers based on the membership tiers and level of importance

I am seeking assistance in implementing a date selection functionality with different priority levels assigned to customers. Below is an explanation of the criteria: Customers with level 1 can choose dates from today up to 5 days in the future Cust ...

JavaScript - Merging the two JSON requests into a unified object

Is there a way to merge two different JSON responses into a single object for easy data manipulation? I've explored various solutions, but none seem to align with my current code structure. Given that I'm new to this, it would be incredibly hel ...

Accessing the current state outside of a component using React Context

As I delve into creating a React application, I find myself in uncharted territory with hooks and the new context API. Typically, I rely on Redux for my projects, but this time I wanted to explore the context API and hooks. However, I'm encountering s ...

How can a loading circle be displayed upon clicking a button on a PHP website using JavaScript?

As a newcomer to the world of JavaScript programming, I'm facing a challenge that seems deceptively simple. My goal is to display a loading circle when a user clicks on an upload button, trigger external PHP code for image processing, and then make th ...

Tips for creating a multitude of components

I have my react code in a single component and I am wondering how to split it into two components for the images container and showroom images. import React, { Component } from 'react'; export default class App extends Component { render() { ...

Having trouble with ESLint in VSCode? The ESLint extension seems to be ignoring linting rules after starting a new project within VSCode

I recently started using the ESLint extension in my VSCode editor for my React project. After creating the starter files, I ran the following command in my terminal: eslint --init This allowed me to choose the AirBnb style guide with React, which generat ...

Retrieve the value of a property in a JavaScript object by specifying a dynamic key for the property

As I work on my current project, I find myself immersed in a world of SVG animations. The challenge lies in triggering these animations as the user scrolls down to view the SVGs. To address this, I took the approach of creating functions for each Snap.SVG ...

HTMLMediaElement does not have the setSinkId method

I am currently in the process of developing a WebRTC application using Angular, with the goal of managing audio output through the setSinkId() method within HTMLMediaElement. However, when attempting to use this method, I am encountering an error message s ...

"NextAuth encounters an issue while trying to fetch the API endpoint: req.body

Trying to implement authentication in my Next.js app using NextAuth.js, I've encountered an issue with the fetching process. Here's the code snippet from the documentation: authorize: async (credentials, req) => { const res = await fetch ...

Struggling to generate components using JQuery

I'm currently working on a form that checks the availability of a username using jQuery. Here is the initial form code: <form> <input id="checkuser" type="text" name="user" placeholder="Your username"/> </form> Below is the jQuer ...

What is the best way to ensure TypeScript recognizes a variable as a specific type throughout the code?

Due to compatibility issues with Internet Explorer, I find myself needing to create a custom Error that must be validated using the constructor. customError instanceof CustomError; // false customError.constructor === CustomError; // true But how can I m ...

How can Observables be designed to exhibit both synchronous and asynchronous behavior?

From: Understanding the Contrasts Between Promises and Observables In contrast, a Promise consistently operates asynchronously, while an Observable can function in synchronous or asynchronous manners. This presents the opportunity to manipulate code in ...

Sorting files in jquery file upload

Has anyone had experience using the jQuery-File-Upload library from https://github.com/blueimp/jQuery-File-Upload? I'm currently facing an issue and wondering if anyone could assist me in sorting the files in a different manner. By default, this scrip ...

Troubleshooting: Android compatibility issues with dynamic source for HTML 5 video

My HTML5 video with dynamic source loaded using JavaScript is functioning properly in a web browser but encountering issues within an Android PhoneGap build application. Take a look at the code snippet below: JavaScript code: $('#video_player' ...

Executing Bower installation within a corporate proxy network

Encountering Error : ECONNREFUSED Request to https://bower.herokuapp.com/packages/bootstrap-datepicker failed: connect ECONNREFUSED while attempting Bower Install from Package Manager Console. I came across suggestions in a different discussion on how to ...

Error: Unexpected identifier in jQuery ajax line

I'm currently encountering an issue with my jQuery ajax call that's throwing an "Uncaught SyntaxError: Unexpected identifier" error at line 3. For confidentiality reasons, I have omitted the original URL. However, even after removing the csrHost ...

The publish-subscribe feature appears to be ineffective

Recently starting with meteor, I learned about the importance of removing autopublish. So, I decided to publish and subscribe to a collection in order to retrieve two different sets of values. Here is the code on my meteor side: Meteor.publish('chann ...