Home > Blockchain >  How can I parse random string to an object javascript
How can I parse random string to an object javascript

Time:09-02

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

CodePudding user response:

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));

CodePudding user response:

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":"[email protected]","Address":"123 Doe Street"}'
var theobj = JSON.parse(thestring);

Resulting in the object:

{
    Name: "Jon Doe",
    Email: "[email protected]",
    Address: "123 Doe Street"
}
  • Related