Decoding a serialized string into an object

I have a data string that is serialized in the format a=4&b=2&c=7. I am looking to convert this string into an object where each key-value pair is represented like this: { a:4, b:2, c:7 }. When I use serializeArray(), it only gives me an array with elements like this:

[0: { name: "a", value:4 } 1: { name: "b", value:2 }]

Is there a way to properly serialize a form into an object?

Appreciate any help on this matter!

Answer №1

To tackle this issue, I recommend splitting the string and then analyzing each element of the resulting array in the following way:

const myString = 'a=4&b=2&c=7';

const splitString = myString.split('&');

const newObject = {};
splitString.forEach((item, index) => {
  newObject[index] = {
    name: item.substring(0, item.indexOf('=')),
    value: item.substring(item.indexOf('=') + 1)
  }
});

console.log(newObject);

Check out the Fiddle for a live demonstration: https://jsfiddle.net/someUser/abc123xyz/

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

Error: Attempting to access property 'question' of an undefined value

Trying to render information from a local .json file using Javascript functions, I encountered an error in the console for const answer despite being defined. I temporarily commented it out to test the function, only to receive the same TypeError for quest ...

What is the best way to play a random song when the user clicks a button?

My goal is to develop a website where users can click on an image and have a random song play from a playlist. I currently have a functioning code that activates one song, but it fails when adding multiple songs to the mix. <html> <head> ...

How can audio be efficiently streamed to the browser in small chunks using JavaScript?

I am currently working on setting up an internet radio station where I want to easily switch songs and overlay sounds. My goal is to limit the audio rate so that the feed can be adjusted before being sent out. Additionally, I would like to provide continuo ...

What is the best way to transfer a string value from one class to another in order to utilize JSON?

I am currently facing an issue with passing a string value from one class to another. In my main class, I have two spinners and a date picker. The first spinner is for selecting the location and the second one is for choosing the stock point name. When a l ...

Converting a TypeScript array into a generic array of a specific class

I am attempting to convert a JSON source array with all string values into another array of typed objects, but I keep encountering errors. How can I correct this code properly? Thank you. Error 1: There is an issue with converting type '({ Id: string ...

Transitioning from using lerna to adopting pnpm

We are in the process of transitioning our project from Lerna to PNPM and we currently have a script that we run. Here are the commands: "postinstall": "npm run bootstrap" "bootstrap": "lerna bootstrap --hoist", &quo ...

Combining strings with objects in Javascript: A step-by-step guide

In the code snippet provided, I am combining variables to create a path to another existing object and its attribute. The issue is that I always receive a string, but I would like to somehow convert it into an object. // SET CUSTOM CONTENT FOR COLUMN IF ...

Having trouble accessing JSON data from a Google spreadsheet?

Yesterday I was successfully retrieving JSON data from a spreadsheet, but now it's returning null. Strangely, I am not able to fetch JSON from a particular spreadsheet file anymore. However, if I create a new spreadsheet and use the exact same code, i ...

Tips for updating the appearance of a specific column in React Native

I've been working on creating a matrix-style table design to show available seats in a bus! I'm iterating through 2D and 3D arrays to achieve this layout! Here is an image of the current output: https://i.sstatic.net/oNtKI.jpg In the image, yo ...

Parameterized query causing JavaScript error

As I struggle with this issue for more than a day now, a scenario unfolds where a user clicks on a link of a book name triggering me to read that book's name. Subsequently, an Ajax request is made to a Jersey resource within which a method in a POJO c ...

Obtain the unique identifiers for each element within an array and attach them to the option values for each item

Forgive me for any misuse of terms, as I am relatively new to Javascript. However, I hope I can describe the desired result effectively in order to receive assistance with my inquiry. Within the code snippet below, there is an array named dates that outpu ...

Tips for transferring a JSON object from an HTML document to a JavaScript file

Here is the code snippet: <script id="product-listing" type="x-handlebars-template"> {{#each productsInCart}} <tr> <td> <div class="imageDiv"> <img ...

`Is there a way to modify the attribute text of a JSON in jQuery?`

I'm attempting to modify the property name / attribute name of my JSON object. I attempted it like this but nothing seems to change. After reviewing the input JSON, I need to convert it to look like the output JSON below. function adjustData(data){ ...

Struggling to showcase information from a JSON file within an embed on a webpage

I am struggling to display the data from my JSON file in an embed. I need assistance with finding a solution for this issue. Here is the content of the JSON file: { "Slims Mod Bot": { "Felix\u2122": 2, "Dus ...

The modification of HTML styles

How can I change the style (width, color etc) of all 8 functions like this? function my(){document.getElementById("question1").innerHTML="THIS QUESTION"+ "<br>" +"<button onclick=answer1() id=ques1 >first answer</button>" +"<button ...

The use of `slot` attributes in Ionic has been deprecated and flagged by the eslint-plugin-vue

I encountered an error message while using VS Code: [vue/no-deprecated-slot-attribute] `slot` attributes are now considered deprecated. eslint-plugin-vue https://i.sstatic.net/DUMLN.png After installing two plugins in .eslintrc.js, I have the following c ...

ReactJS and JavaScript offer a convenient solution for extracting the most recent date from an array of date fields during the selection process

I have a table in ReactJS that displays an array of items. Each item has the following fields: id, requested_date, and location Additionally, there is another field called "date" which is located outside of the array. This "date" should always display th ...

Struggling to determine whether an array contains data or is void in ReactJS?

In the state, I have an array and I set the default value of my state to an empty array []. After loading an API request, I need to display a loader until the data is ready. So, I am using a condition like this: (if the array length === 0, the loader wil ...

The alert box is not displaying, only the text within the tags is visible

Trying to implement an alert message for logged-in users. A successful login will trigger a success message, while incorrect username or password will display an error. function showMessage(response) { if (response.statusLogged == "Success login") { ...

Error encountered while executing ExpressJs function that was converted to a promise

Understanding how errors are handled in promises can be a bit tricky, especially for someone new to promises like myself. I'm trying to make the most of them, but I'm not quite there yet. Here is the code snippet I'm working with: app.list ...