js deep serialize url array

Solutions on MaxInterview for js deep serialize url array by the best coders in the world

showing results for - "js deep serialize url array"
Jagger
30 Aug 2019
1/*
2	most answers in the thread do not serialize multi-level objects
3	this is probably bloated but works for nested arrays in objects
4	
5    usage:
6    
7    let querystring = flatten(myComplexJsObject)
8*/
9
10function flatten(object, prefix = ''){
11    let flatObject = Object.keys(object).reduce((carry, key) => {
12        const pre = prefix ? prefix + `[${key}]` : '';
13
14        if (Array.isArray(object[key])) {
15            carry = object[key].reduce((array, value, index) => {
16                array[(pre || key) + `[${index}]`] = value;
17                return array;
18            }, carry);
19        } else if (object[key] && typeof object[key] === 'object') {
20            Object.assign(carry, flatten(object[key], pre || key));
21        } else {
22            carry[pre || key] = object[key];
23        }
24
25        return carry;
26    }, {});
27  
28  	if(!flatObject || !flatObject.length) return '';
29	let querystring = flatObject.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`).join('&');
30	return querystring ? '?' + querystring : querystring;
31};