0

So I have a string below 'user.name.firstName=Anatoliy&user.name.lastName=Klimov&user.vip=true'

I've to parse it to Object looks like

{
"user": {
  "name": {
    "firstname": "",
    "lastname": ""
 {
  "vip": true
 }
}
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
German
  • 3
  • 2
  • So, you want to convert that query string to a object? – Cerbrus Sep 02 '22 at 11:14
  • Dupe: [Convert javascript dot notation object to nested object](https://stackoverflow.com/questions/7793811/convert-javascript-dot-notation-object-to-nested-object) –  Sep 02 '22 at 11:19
  • Does this answer your question? [How can I get query string values in JavaScript?](https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript) – Nick Sep 02 '22 at 12:17

2 Answers2

0

Here's an approach

const data = 'user.name.firstName=Anatoliy&user.name.lastName=Klimov&user.vip=true';

const constructObject = (str) => {
    const paths = str.split('&');
    const result = {};

    paths.forEach((path) => {
        const [keyStr, value] = path.split('=');
        const keys = keyStr.split('.');

        let current = result;
        for (let i = 0; i < keys.length - 1; i++) {
            if (!current[keys[i]]) {
                current[keys[i]] = {};
            }
            current = current[keys[i]];
        }
        current[keys.pop()] = value;
    });
    return result;
};

console.log(constructObject(data));
Abito Prakash
  • 4,368
  • 2
  • 13
  • 26
0

There is a function JSON.parse() that can convert your string into an object.

You can search online about how to format the string for this function, but I have an example below which may help.

var thestring = '{"Name":"Jon Doe","Email":"jon@doe.com","Address":"123 Doe Street"}'
var theobj = JSON.parse(thestring);

Resulting in the object:

{
    Name: "Jon Doe",
    Email: "jon@doe.com",
    Address: "123 Doe Street"
}
Shivek
  • 1