Answers for "object to url params"

2

js object to querystring

const params = {foo:"Hi", bar:"there"}
const queryString = new URLSearchParams(params).toString();

console.log(queryString);
Posted by: Guest on January-05-2021
1

object to url params js

new URLSearchParams(obj).toString();
Posted by: Guest on September-24-2021
0

object params to url

$.param( obj )
Posted by: Guest on December-29-2020
0

js deep serialize url array

/*
	most answers in the thread do not serialize multi-level objects
	this is probably bloated but works for nested arrays in objects
	
    usage:
    
    let querystring = flatten(myComplexJsObject)
*/

function flatten(object, prefix = ''){
    let flatObject = Object.keys(object).reduce((carry, key) => {
        const pre = prefix ? prefix + `[${key}]` : '';

        if (Array.isArray(object[key])) {
            carry = object[key].reduce((array, value, index) => {
                array[(pre || key) + `[${index}]`] = value;
                return array;
            }, carry);
        } else if (object[key] && typeof object[key] === 'object') {
            Object.assign(carry, flatten(object[key], pre || key));
        } else {
            carry[pre || key] = object[key];
        }

        return carry;
    }, {});
  
  	if(!flatObject || !flatObject.length) return '';
	let querystring = flatObject.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`).join('&');
	return querystring ? '?' + querystring : querystring;
};
Posted by: Guest on July-06-2020

Code answers related to "Javascript"

Browse Popular Code Answers by Language