Hello, community. I need to convert an object to the parameter string for a URL like this:

Entry object:

var obj = { a: 4, b: { c:5, d: { e: 33, f:13 }, g:1 }, h: [1,2] }; 

Parameter line on output:

 a=4&b[c]=5&b[d][e]=33&b[d][f]=13&b[g]=1&h[]=1&h[]=2 

Parameter string in a more readable form for comparison with the source object:

 a=4 & b[c]=5 & b[d][e]=33 & b[d][f]=13 & b[g]=1 & h[]=1 & h[]=2 

I am writing a program on Node.JS. If you know such a function, or a package with such a function, or wrote it yourself, share it. Thank you in advance.

  • 2
    JSON.stringify (), transfer to the server, and on the server is already the reverse operation. This is certainly not the answer to the directly posed question, but without bicycles. - ReinRaus
  • Here it is a little bit different. I am writing a rather complicated application and on the page, for example, several tables are displayed per page. Those. The table can be opened on page 5, and the second at 2. When the user clicks on the pager on page 3 at table 2, table 3 should open in this table 2, and the first one should remain fifth. And the pages are determined from the url: for example, pager1 = 5 & pager2 = 2, but the tables do not need to know about the existence of each other. Therefore, the path was chosen that the page button will take the req.query object and change the value of its teacher in it, and convert it to a link. - MuFF

1 answer 1

He himself wrote the required function. ) For those who want to know the correct answer:

 function encode(obj){ function objToArray(obj, path){ if(!path) path = []; var result = []; for(var i in obj) if(typeof obj[i] == 'object') result = result.concat(objToArray(obj[i], [].concat(path, [i]))); else result.push({path: [].concat(path, [i]), value: obj[i]}); return result; } function arrayToURL(array){ var vars = []; array.forEach(function(item, i){ var parts = []; item.path.forEach(function(part, i){ parts.push(i == 0 ? part : ('[' + part + ']')); }); vars.push([parts.join(''), item.value].join('=')); }); return vars.join('&'); } return arrayToURL(objToArray(obj)); } module.exports = encode; 

If you file an object like this:

 var obj = { a: 1, b: { c: { d: 'sd', r: 'qqq' }, h: 9 }, zz: [1,2,3] }; 

So the output is this line:

 a=1&b[c][d]=sd&b[c][r]=qqq&b[h]=9&zz[0]=1&zz[1]=2&zz[2]=3 

Thanks to all! )

  • Something I can not understand how to close the question now .. - MuFF
  • one
    Why close it? Maybe in half an hour someone will post their more optimal code, or an indication of a standard function that does the same. Or in a year it will happen, not the point. - ReinRaus
  • Well, if so .. ok then ..) - MuFF