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 transform this object with strings into a normal one?

I have the following object:

const updatedFields = {
    "user.name": "potato",
    "plan": "diamond"
}

I expect it to be:

const obj = {
    user: {
        name: "potato"
    },
    plan: "diamond"
}

The code I am currently running:

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

const updatedFields = {
    "user.name": "potato",
    "plan": "diamond"
}

const obj = {}

setpath = ([p,...ps], v, o) => ps.length ? setpath(ps, v, o[p]) : o[p] = v
Object.entries(updatedFields).forEach(([p,v]) => setpath(p.split("."), v, obj))

console.log(obj)

The error I’m getting:

setpath = ([p,...ps], v, o) => ps.length ? setpath(ps, v, o[p]) : o[p] = v
                                                                       ^

TypeError: Cannot set property 'name' of undefined
    at setpath (/tmp/8LYm4RhWvR.js:8:72)
    at setpath (/tmp/8LYm4RhWvR.js:8:44)
    at Object.entries.forEach (/tmp/8LYm4RhWvR.js:9:50)
    at Array.forEach (<anonymous>)
    at Object.<anonymous> (/tmp/8LYm4RhWvR.js:9:31)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)

How can I solve it?

>Solution :

o[p] or the user is undefined initially. So, when you try to set name property of the user object, it will throw an error.

You can use the Logical nullish assignment to set a value, if it doesn’t exist. So, set o[p] ??= {}

const updatedFields = {
    "user.name": "potato",
    "plan": "diamond"
}

const obj = {}

const setpath = ([p,...ps], v, o) => ps.length ? setpath(ps, v, o[p] ??= {}) : o[p] = v
Object.entries(updatedFields).forEach(([p,v]) => setpath(p.split("."), v, obj))

console.log(obj)

Also, there are alternatives this here:

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