Home > Blockchain >  How can I transform this object with strings into a normal one?
How can I transform this object with strings into a normal one?

Time:09-29

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:

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?

CodePudding user response:

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:

  • Related