Transforming a hierarchical array into a string based on a specific condition

Seeking assistance in properly formatting data using the reduce method

const testData = { a: [1], b: [2, 3, 4], c: [] };

Objective is to convert to: a=1&b=2,3,4 Current output: a=1&b=2,3,4&

const createUrlString = params =>
    Object.keys(params)
        .map(
            attr => (params[attr].length ? `${attr}=${params[attr].join(',')}` : '')
        )
        .join('&');

const testData = { a: [1], b: [2, 3, 4], c: [] };
const filterString = createUrlString(testData);

Answer №1

The "filter" technique is the solution in this scenario.

const generateUrl = data =>
    Object.keys(data)
        .map(
            attribute => (data[attribute].length ? `${attribute}=${data[attribute].join(',')}` : '')
        )
        .filter(urlString => urlString)
        .join('&');

Answer №2

Instead of utilizing the array#map function, you can opt for the array#reduce method. When dealing with empty array values, inserting a '' string results in the array#join function appending an & at the end.

const sampleData = { x: [5], y: [6, 7, 8], z: [] };
var finalResult = Object.keys(sampleData).reduce((output,key) => {
  if(Array.isArray(sampleData[key]) && sampleData[key].length) {
    output.push(`${key}=${sampleData[key].join(',')}`);
  }
  return output;
},[]).join('&');

console.log(finalResult);

Answer №3

To transform an object into a multidimensional array, you can utilize the Object.entries() method.

Object.entries({ name: 'John', age: 30 });

Executing the above code will result in:

[ ['name', 'John'], ['age', 30] ]

Check out the code snippet below:

const createQueryString = queries =>
  Object.entries(queries)
    .map( item => item[0]+"="+item[1].join(","))
    .join('&');

const sampleData = {
  x: [10],
  y: [20, 30, 40],
  z: []
};
const queryString = createQueryString(sampleData);
console.log(queryString)

Answer №4

Make sure to start by sorting out the data:

const exampleData = { x: [5], y: [6, 7, 8], z: [] };
let sortedData = Object.entries(exampleData).filter(e => e[1].length > 0);//Sort out empty values
var finalResult = sortedData.map(e => {
    e[1].join(',');
    return e.join('=');
}).join('&');

Answer №5

Include & always with non-empty values and remove the last one at the end

function generateUrlParams(params) {
    return Object.keys(params)
        .map(
            key => (params[key].length ? `${key}=${params[key].join(',')}&` : '')
        )
        .join('');
}

const exampleData = { a: [4], b: [7, 8, 9], c: [] };
const urlString = generateUrlParams(exampleData);
console.log(urlString.slice(0, urlString.length - 1));

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

AngularJS Perspectives: Unveiling the Secrets of Successful Implementation

Do you have any tips on troubleshooting AngularJS views? I found a demo at AngularJS: ngView, but the provided jsfiddle doesn't seem to work. I've been trying to play around with it, but still haven't had any success. This is the code I&apo ...

On top of the world always is Mesh or Sean

Currently I am working on a 3D diagram, possibly using a bar or line graph. I have been using three.js version 60 as most of my code has already been developed with this version. However, I am facing an issue with adding legends to the diagram. The 3D obje ...

Encountering npm install failure post updating node version

When attempting to execute npm i, the following error message is now appearing: npm i npm ERR! path /home/ole/.npm/_cacache/index-v5/37/b4 npm ERR! code EACCES npm ERR! errno -13 npm ERR! syscall mkdir npm ERR! Error: EACCES: permi ...

What is the most effective method for sorting through an array to generate a new array?

Is there a way to filter items from an array based on a specific string and store them in a new array for further manipulation? If so, what would be the most efficient approach to achieve this? Here is the current progress of my code: for (var i = 0; i & ...

Issue: Error message - Unhandled promise rejection: NodeInjector error - ControlContainer not found

I'm having trouble validating a form and encountering an error. I tried implementing the suggestions provided in the following threads without success: Getting error suddenly in Angular Error: NodeInjector: NOT_FOUND [ControlContainer] Using forms i ...

Crashes within an HTML5 Canvas

Having recently started to explore Javascript and working with canvas elements, I've encountered a roadblock when trying to implement collision detection for the canvas walls. Typically, I have a small square drawn on the canvas that I can move aroun ...

In Wordpress, data attributes are set using an array with key-value pairs

I have organized a list of product details in an array. I want to assign each key from the array as a data-attribute and its corresponding value as the data-attribute's value. <li data-name="product1" data-price="49.99" data-rating="4.5"></l ...

Interactive button visual effect

I have a piece of code that currently plays audio when I click on an image. However, I am looking to modify it so that not only does clicking on the image play the audio, but it also changes the image to another one. Can anyone assist me with this? Here i ...

Executing a JavaScript function following a PHP form submission

I've been struggling to understand why the checkDates() function is not being called after submitting the form. The checkForm() JS function works perfectly fine, but for some reason, checkDates() doesn't seem to work. I even tried moving it above ...

Troubleshooting Error in Angular2 ngFor: "Encountered issue with reading property '0' of undefined"

I am attempting to retrieve data from a JSON file in order to create a form. Below is a snippet of my template: <div class="form-group"> <label for="power">Power</label> <select class="form-control" id="power" required> ...

When I attempted to POST a js::array in JSON, the response returned "undefined:undefined"

I have a javascript array on the frontend that I need to send to my Tomcat server. Currently, I am using the following code but encountering issues: console.log("preview list. postUsers()"); console.log(Ext.getCmp("preview-container").get ...

What is the best way to prevent text from being dragged within a contenteditable div?

Currently, I am working on a contenteditable div. This div has a default behavior that allows you to drag pieces of text around. I have tested this behavior on Chrome/Windows only so far. https://i.sstatic.net/IWLsY.gif I am looking for a way to disable ...

Updating the organization of the models directory in Loopback

I am looking to update the structure of the models folder. As per the documentation, I can make changes to the json config file which is typically set up like this: { "_meta": { "sources": [ "loopback/common/models/**/*", "loopback/serve ...

Change the behavior of a submit button to trigger a custom JavaScript function instead

I am faced with a challenge where I need to override the default functionality of a button in code that cannot be altered. Instead, I must ensure that when the button is clicked, a custom JavaScript method is called rather than submitting the form as it no ...

Angular encountering issue with HTTP service not functioning as expected

I have been encountering issues while trying to retrieve data using JSONPlaceholder in my service. Despite my efforts, I have not been successful in fetching any data. I would greatly appreciate any assistance in resolving this matter. user.component.html ...

The Facebook SDK fails to activate in Internet Explorer

I am currently working on implementing a Facebook login using the JavaScript SDK. Everything is functioning correctly in most browsers, but I am experiencing issues with certain versions of Internet Explorer. The login functionality is not working on my l ...

Encountering Err_Connection_Refused while working with MVC WebAPI 2 and AngularJS

Seeking guidance on WebAPI, AngularJS, and .NET Authentication, I am currently following a tutorial mentioned HERE. The tutorial is brief (~under 10 mins), but I encountered an error stating Failed to load resource: net::ERR_CONNECTION_REFUSED. Typically, ...

Tips on how to properly handle Promises in a constructor function

My Angular Service is currently making http requests, but I am looking to retrieve headers for these requests from a Promise. The current setup involves converting the promise to an Observable: export class SomeService { constructor(private http: HttpCl ...

iOS Device Identification Code: OneSignal Player ID

By using OneSignal and Firebase, I successfully stored the user's playerIDs as a node. To send notifications to multiple users, I created an array containing each playerID (String). However, when attempting to send a notification, I encountered the f ...

Guide to fetching input control value dynamically inserted via javascript

In my PHP view, I have implemented a button that adds textboxes to the page within a form. However, when trying to retrieve the value of these dynamically added textboxes in my PHP controller, the value is not present. Is there a solution for obtaining t ...