A guide on breaking down a URL string containing parameters into an array with the help of JavaScript

I need help splitting a long string into an array with specific index structure like this:

fname=bill&mname=&lname=jones&addr1=This%20House&...

I am looking to have the array set up as shown below:

myarray[0][0] = fname
myarray[0][1] = bill
myarray[1][0] = mname
myarray[1][1] = 
myarray[2][0] = lname
myarray[2][1] = jones
myarray[3][0] = addr
myarray[3][1] = This House

The actual URL is longer than the example provided. So far, I have attempted to achieve this using the following code:

var
    fArray = [],
    nv = [],
    myarray = [];

fArray = fields.split('&');

// split it into fArray[i]['name']="value"
for (i=0; i < fArray.length; i++) {
    nv = fArray[i].split('=');
    myarray.push(nv[0],nv[1]);
    nv.length = 0;
}

The result should be stored in 'myarray', however, I am encountering an issue where I am getting a one-dimensional array instead of the desired two-dimensional array.

Subsequently, I plan to search for a specific key like 'lname' and retrieve its corresponding index. For instance, if it returns '3', I can then access the last name using myarray[3][1].

Do you think my approach makes sense or am I making it too complex?

Answer №1

It seems that when you use the line myarray.push(nv[0],nv[1]);, it actually adds two elements to the array myarray instead of a single pair as expected. To achieve your desired result, you can use myarray.push( [nv[0],nv[1]] ) (with brackets), or myarray.push(nv.slice(0, 2)).

If you want a more streamlined approach, consider utilizing Array.map:

var q = "foo=bar&baz=quux&lorem=ipsum"; 
         
var vars = q.split("&").map(function (kv) {
               return kv.split("=", 2);
           });

When searching, I recommend using array.filter:

var srchkey = "foo";
var matches = vars.filter(function (v) { return v[0] === srchkey; });

Note: array.filter will always return an array. If you only need a single value, consider using array.some or creating a custom search algorithm.

Answer №2

for (let j = 0; j < new_array.length; j++) {
    values = new_array[j].split('=');
    customArray.push([values[0],values[1]]);
}

Avoid using values.length = 0; as it is unnecessary since you are already initializing values within each iteration of the for loop.

It is recommended to declare let j in the for-loop to prevent potential conflicts with a global variable named j.

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

Place the Drawer element at the bottom of the menu

Is there a way to position the menu point at the bottom of the screen? It would be great if we could easily customize the style of the navigation options for each element. Check out my App Navigator below: const AppNavigator = createDrawerNavigator( ...

React-Tooltip trimming

Currently, I am facing a dilemma that requires some resolution. The issue at hand is related to the placement of React-Tooltip within the List element. Whenever it's positioned there, it gets clipped. On the other hand, placing it at the bottom isn&a ...

The v-model in Vue does not function correctly when used with a single index within an array

I am encountering a situation with a series of input fields, including a checkbox and a dropdown button in each row. Additionally, there is a button to add a new row of inputs. When the checkbox is checked, it should disable the dropdown menu and make it ...

ReactJS fetching previous data through POST request

I am facing an issue while trying to replicate Google Translate. I have an API that sends and returns data as expected during the first translation attempt. However, after changing the text and attempting another translation, it sends the updated text but ...

Sharing JavaScript code between Maven modules can be achieved by following these steps

My Maven project has a unique structure that includes: "Base" module -- containing shared Java files -- should also include shared JavaScript files Module 1 -- using shared Java files as a Maven dependency -- should utilize shared JavaScript files throug ...

Attempting to access an index of type 'String' on a value of type 'String' is not allowed

Can anyone assist me with this issue I am facing? I want to display a name on a table view cell from an array called postFromFriends. However, when I attempt to access the name in the array, I receive an error stating "Cannot subscript a value of type &apo ...

How can we dynamically update an environment variable for the IP address before running npm start in a React application?

Currently, I am attempting to automatically set the REACT_APP_DEPLOY_DOMAIN variable in the .env file. Here is one approach that I have implemented to address this challenge. In the script below, I am extracting my IP address: const os = require("os"); ...

What could be causing the code to malfunction and prevent window.ethereum from working properly?

While attempting to develop a dApp, I have encountered an issue with the browser in Visual Studio Code not recognizing the Ethereum connection, despite having installed MetaMask on the active browser session. Here is a snippet of my code used to test the c ...

Issue arises when isomorphic-dompurify is used alongside dompurify in Next.js 13 causing compatibility problems

I am currently facing a compatibility problem involving isomorphic-dompurify and dompurify in my Next.js 13 project. It appears that both libraries are incompatible due to their dependencies on canvas, and I am struggling to find a suitable alternative. M ...

Exploring the Contrast between window.location.href and top.location.href

I'm curious about the distinction between window.location.href and top.location.href. Can anyone explain this to me? Furthermore, I'd like to know when it's appropriate to use each one. Which option is more suitable for redirection after a ...

Unforeseen SyntaxError: Unexpected symbol detected

Encountering an issue while attempting to send raw data as parameters in express. Specifically, there is an error occurring at the 'fields' variable... function getWithQuery(req,res){ console.log(req.params); var query = {name: new RegEx ...

Traversing through each element using Array method

I need to create a redux function that will add a specified number n to the fourth element of an array every time a button is clicked. However, if the element is either L or M, I do not want the addition to occur. For example, starting with this initial a ...

Execute my function when the Redux state changes in the store in ReactJS

I am facing a specific issue in my React-Redux application. I am using Redux-saga to communicate with a REST API, which does not return a promise. Within my application, I also utilize state (in addition to the store) that I wish to update after receiving ...

iPhone 6 (iOS) users may face compatibility issues with iframe and fancy box features

I am currently learning how to use jQuery and the fancybox library. In my Angular 1 and Ionic project, I have successfully implemented fancybox with an iframe. Everything works perfectly on browsers and Android devices, but on iOS, a loader icon appears an ...

What is the location where nvm saves its node.js installations?

I'm having trouble locating where node.js installations are stored after downloading and installing through commands like: nvm install 5.0 Can anyone provide some insight on this? ...

Tips for integrating v-virtual-scroll with v-table?

My Vuetify table is handling a large amount of data – 300 rows with 20 columns, some of which have calculated rowspans. To improve performance, I'm considering using the v-virtual-scroll component. I came across this sample code, which doesn't ...

What methods can I use to sort content by its rating?

I am embarking on my inaugural project and attempting to construct a product filtering system. So far, I have successfully implemented search and category filters; however, configuring the rating filter has proven to be challenging. Here is an excerpt of ...

Displaying outcomes solely based on JSON upon choosing a filter

Goal I aim to only show results once their respective state is chosen. Currently, all results are displayed automatically upon page load. I prefer if nothing is shown initially. Only when a state is selected should the corresponding results appear. Bac ...

How can I deactivate all form controls within an AngularJS form?

To prevent any changes to the form components when the view button is clicked, I need to disable them. Here is my form: <form action="#" class="form-horizontal" > <div class="form-group"> <label for="fieldname" class="col-md-3 cont ...

using post request axios to send parameters

I am looking to make a post request using axios with an object as the payload. employee:{ name: 'test', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0d79687e794d6a606c6461236e6260">[email ...