K
K
kachurinets2018-11-08 12:47:45
JavaScript
kachurinets, 2018-11-08 12:47:45

How to serialize nested object?

I want to translate the nested object into a string to send to the backend.
https://jsfiddle.net/rwcjapft/
There is such an object

let obj = {
  page: "1",
  search: {title: "gfsg", without_complex: false},
  size: "10",
  items: 323
}

I need to get the output
page=1&search[title]=gfsg&search[without_complex]=false&size=10&items=323

how to get this output?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2018-11-08
@kachurinets

const serialize = (obj, path) =>
  Object.entries(obj).map(([ k, v ]) => {
    const p = path ? `${path}[${k}]` : k;
    return v instanceof Object ? serialize(v, p) : `${p}=${v}`;
  }).join('&');

V
Vitaly Stolyarov, 2018-11-08
@Ni55aN

There is a ready-made solution for this: https://github.com/ljharb/qs

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question