简体   繁体   中英

create nested object from string JavaScript

I have a string like this:

let user = "req.user.role" 

is there any way to convert this as nested objects for using in another value like this?

let converted_string = req.user.role

I know I can split the user with user.split(".")

my imagination:

let user = "req.user.role".split(".")
let converted_string = user[0].user[1].user[2]

I found the nearest answer related to my question: Create nested object from query string in Javascript

Try this

 let user = "req.user.role"; let userObj = user.split('.').reduceRight((obj, next) => ({ [next]: obj }), {}); console.log(userObj);

Or this, for old browsers

 var user = "req.user.role"; var userArray = user.split('.'), userObj = {}, temp = userObj; for (var i = 0; i < userArray.length; i++) { temp = temp[userArray[i]] = {}; } console.log(userObj);

The function getvalue() will return the nested property of a given global variable:

 var user="req.user.role"; var req={user:{role:"admin"}}; function getvalue(str){ return str.split('.').reduce((r,c,i)=>i?r[c]:window[c], ''); } console.log(getvalue(user));

I'll take my shot at this:

 let user = "req.user.role" const trav = (str, o) => { const m = str.split('.') let res = undefined let i = 0 while (i < m.length) { res = (res || o)[m[i]] if (,res) break i++ } return res } const val = trav(user: { req: { user: { role. "admin" } } }) console.log(val)

this function will traversed the passed in object for the entire length of the provided string.split "." list returning either a value or undefined.

You can do it like this:

let userSplitted = "req.user.role".split('.');
let obj, o = obj = {};

userSplitted.forEach(key=>{o=o[key]={}});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM