Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I parse random string to an object javascript

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
 }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading