-2

Example of complex object which i want to serialize, so I can use it in url as query param

 var query =  {
        "page": {
            "number": 1,
            "size": 50
        },
        "sort": "engagement_total",
        "sort_direction": "asc",
        "filters": {
            "engagement_total": {
                "type": "range",
                "value": [
                    21,
                    46
                ]
            }
        }
    }

JSON.stringify(query)

result with stringify

'{"page":{"number":1,"size":50},"sort":"engagement_total","sort_direction":"asc","filters":{"engagement_total":{"type":"range","value":[21,46]}}}'

Desired result

filters%5Bengagement_total%5D%5Btype%5D=range&filters%5Bengagement_total%5D%5Bvalue%5D%5B%5D=21&filters%5Bengagement_total%5D%5Bvalue%5D%5B%5D=46&page%5Bnumber%5D=1&page%5Bsize%5D=50&sort=engagement_total&sort_direction=asc
loki
  • 187
  • 2
  • 14
  • @jabaa yep, that gives me this "%5Bobject%20Object%5D" with object inside string – loki Aug 24 '22 at 12:16
  • '{"page":{"number":1,"size":50},"sort":"engagement_total","sort_direction":"asc","filters":{"engagement_total":{"type":"range","value":[21,46]}}}' sry i get this – loki Aug 24 '22 at 12:19
  • var s = { "page": { "number": 1, "size": 50 }, "sort": "engagement_total", "sort_direction": "asc", "filters": { "engagement_total": { "type": "range", "value": [ 21, 46 ] } } } undefined JSON.stringify(s) '{"page":{"number":1,"size":50},"sort":"engagement_total","sort_direction":"asc","filters":{"engagement_total":{"type":"range","value":[21,46]}}}' – loki Aug 24 '22 at 12:24
  • omg forget it man, forget about that I added correct code what i got with your suggestion JSON.stringify, its fine if you don't know how to help don't flex on me – loki Aug 24 '22 at 12:34
  • new URLSearchParams(query).toString() this gave me that result with small object that I tried before if you are so worried about that attempt – loki Aug 24 '22 at 12:36
  • You will probably have to do this manually. The URLSearchParams constructor can't handle such nested objects, [quote MDN](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/URLSearchParams#parameters): _"A record of string keys and string values. Note that nesting is not supported."_ – CBroe Aug 24 '22 at 12:40

1 Answers1

4

let obj = {
    "page": {
        "number": 1,
        "size": 50
    },
    "sort": "engagement_total",
    "sort_direction": "asc",
    "filters": {
        "engagement_total": {
            "type": "range",
            "value": [
                21,
                46
            ]
        }
    }
}

var flattenObj = function(data) {
    var result = {};
    function recurse(cur, prop) {
        if (Object(cur) !== cur) {
            result[prop] = cur;
        } else if (Array.isArray(cur)) {
            for (var i = 0, l = cur.length; i < l; i++)
                recurse(cur[i], prop + "[" + i + "]");
            if (l == 0)
                result[prop] = [];
        } else {
            var isEmpty = true;
            for (var p in cur) {
                isEmpty = false;
                recurse(cur[p], prop ? prop + "[" + p + "]" : p);
            }
            if (isEmpty && prop)
                result[prop] = {};
        }
    }
    recurse(data, "");
    return result;
};
let output = flattenObj(obj);
let url = Object.entries(output).map(elem => (elem[0].replace(/\[[0-9]+\]/, '[]') + "=" + elem[1])).join("&")
console.log("url:", url)
console.log("encodeURI:", encodeURI(url))
Sakil
  • 666
  • 3
  • 8