Building a query in Javascript by utilizing object keys and values: a step-by-step guide

I am looking to transform an object with various keys and values into a query string format, for example:

obj1: {
  abc: "Abc",
  id: 1,
  address: "something"
}.

The challenge is that this object is generated dynamically, so the number of keys in it can vary. For instance, another dynamically created object could be:

obj1: {
  test: "123",
  test2: "3333"
}

No matter what the structure of the server's response object is, I need to convert it into a query string, like:

query1 = "test:'123'and test2: '3333'"
query2 = "abc:'Abc' and id: 1 and address: 'something'"

I could attempt something like:

Object.keys(obj1)[0]: obj1[Object.keys(obj1)[0]]

This approach would yield:

abc:'Abc'

However, due to the dynamic nature of the object's keys and length, I am struggling to figure out how to concatenate these pairs into a single string. Any suggestions?

Answer №1

Despite a few minor inconsistencies in the formatting, you can make use of Object.entries, Array#map, and Array#join in the following manner:

const objToQuery = o =>
  Object.entries(o).map(([k, v]) => 
    `${k}: ` + (typeof v === "number" ? v : `'${v}'`)
  ).join(" and ")
;

const obj1 = {
  abc: "Abc",
  id: 1,
  address: "something"
};
const obj2 = {
  test: "123",
  test2: "3333"
};
console.log(objToQuery(obj1));
console.log(objToQuery(obj2));

Answer №2

Getting a little creative by utilizing the built-in URLSearchParams(), then performing some manipulation to replace the characters = and &. It's worth noting that the necessity of quotation marks may vary depending on your specific requirements, as another solution could be more efficient if quotation marks are needed.

const obj1 = {
  abc: "Abc",
  id: 1,
  address: "something"
}

const objToQuery = o => {
  return (new URLSearchParams(Object.entries(o)))
    .toString().replace(/=/g, ': ').replace(/&/g, ' and ')
}



console.log(objToQuery(obj1))

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

Attempting to set up an Ajax webform with various outputs, but encountering issues with functionality

I'm encountering an issue while creating interactive exercises. I want to display correct or incorrect answers immediately after submission using JSON for retrieving responses, as suggested in a forum. However, my AJAX code isn't working at all. ...

The supertest request body cannot be found

Testing my express server POST endpoint using supertest has been a challenge for me. Although everything works perfectly in postman, I encountered an issue when trying to pass body parameters into the test. It seems like the body parameters are not being p ...

Having trouble establishing a new local Windows directory structure with Selenium

After following the guidelines provided here and here, I am striving to ensure that the directory where my results reports are stored is consistently available for each user. new File(sampleFolder).mkdir(); The sampleFolder path displayed in the Eclipse ...

Utilizing Filters to Dynamically Highlight and Unhighlight HTML in Angular

Currently, I am experimenting with creating a series of filters that can dynamically highlight and remove highlighting from generated HTML: Highlight filter: app.filter('highlight', function ($sce) { return function (str, termsToHighlight) ...

Issue occurred while executing the fs.rename() function in a loop in Node.js

I'm currently working on a project that involves organizing uploaded files into folders based on their request ID. I am using express-request-id to retrieve this ID. The issue I am facing is that whenever there are multiple files to be moved, the pro ...

Switch between two AppBars simultaneously while scrolling in Material UI

In my Header.js component, I have two AppBars. The first one is sticky and the second one is not initially visible. As we scroll down, I want the second AppBar to collapse and the first one to stay stickied at the top of the screen. I looked at the Materi ...

The Angular 5 keyup event is being triggered twice

My app is incredibly simple, just a basic hello world. To enhance its appearance, I incorporated bootstrap for the design and ng-bootstrap for the components. Within one of my TS files, you will find the following code: showMeTheKey(event: KeyboardEvent) ...

How can I trigger the opening of an iframe without relying on jQuery when the user clicks on it?

I'm looking to create a UI where the user can click on an image and have an iframe appear on top of the image. Instead of using JQuery, I want to stick with pure JavaScript for this functionality. ...

Tips for transferring data to an entry component in Angular 2 using ng-bootstrap modal

I've been grappling with sending data to a custom modal content component in Angular 2. My objective is to have the flexibility of calling this modal from any other component without duplicating code. Despite my efforts, including referencing the "Com ...

I specified Authorization Bearer in the Fetch API configuration, however, the Request Headers do not contain the necessary Authorization information

Check out the following code snippet: fetch('http://localhost:3000/tasks/', { method: 'GET', mode: 'no-cors', headers: new Headers({ 'Authorization': 'Bearer <jwt_token>' ...

Discovering the audio file URL hidden within javascript code

Is it possible to programmatically locate a link to an audio pronunciation clip on a website? I am in the process of creating a personalized language learning Anki deck. The specific site I am referring to is: When clicking on "Framburður," the audio cli ...

Regular expressions: Capturing characters that come after and before a designated symbol

Is there a way to extract all letters, both before and after an underline "_", in JavaScript using Regex while excluding specific words like "pi", "\Delta" and "\Sigma"? How can this be achieved in Regex JS? /\b([^e|_|\d|\W])&bso ...

Is there a way to group together select values in a dropdown menu under a shared category?

If I have a dropdown menu that looks like for example: <select> <option value="1">1</option> <option value="3">3</option> <option value="2">2</option> <option value="4">4</option> </select&g ...

Exploring the process of retrieving outcomes from Node.js within a Knockout ObservableArray

Below is the Node.js code snippet I have: var http = require('http'); var port = process.env.port || 1337; var MovieDB = require('moviedb')('API KEY'); MovieDB.searchMovie({ query: 'Alien' }, function (err, res) { ...

In just a single line of code, you can iterate through a Record object and retrieve an array of DOM elements

I am working with an object type MyType = 'name' | 'base' | 'six'; obj: MyType = { 'name': {key: 'm1'}, 'base': {key: 'm2'}, 'six': {key: 'm3'}, } My goal is ...

Generating a dynamic list by utilizing database data once a button has been clicked

I'm looking to create a feature on my website where clicking on a button will populate a paragraph below it with data retrieved from a database query containing two columns. The first column provides the text for a list, while the second column contai ...

Efficient Ways to pass information to an Object within a nested function

const http = require('https'); exports.ip = async (req, res) => { const ip = req.body.ip; const ip_list = ip.trim().split(' '); const count = ip_list.length; var execution_count = 0; var success = {}; // **Creati ...

Context menu for OpenLayers 3 maps

Is there a way to implement a right-click context menu that displays information about the clicked point? For example, when I right-click on a map, a dropdown menu should appear with options like 'add marker', and it should also show the coordin ...

Struggling to convert my VueJS component from JavaScript to TypeScript, feeling a bit lost

I am new to VueJS and I am facing a challenge converting my VueJS project to use TypeScript. I have been trying to bind functions to certain variables in JavaScript, but I am struggling with accomplishing the same in TypeScript. Even though there are no er ...

Are you familiar with manipulating Arrays or Objects in jQuery?

In JavaScript, we can create objects with keys as strings for similar functionality to an associate array. Check out this example here. For example: ".home-title":[ ["font-size","12px"], ["line-height","16px"], ], However, if you need a ...