0

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

Babak Abadkheir
  • 2,222
  • 1
  • 19
  • 46
  • Like this? https://stackoverflow.com/questions/6393943/convert-javascript-string-in-dot-notation-into-an-object-reference/6394168#6394168 –  Jun 28 '20 at 19:07
  • You find a similar answer and also know the approach ish for the solution. What is your problem here? Did you try anything on your own? – SMAKSS Jun 28 '20 at 19:07
  • @SMAKSS yeah I did , it didnt work. I updated my question – Babak Abadkheir Jun 28 '20 at 19:09
  • 1
    You can't create the first part `req` as a dynamic variable name. It would need to be a property of another object ( even window) and use `[]` notation for all – charlietfl Jun 28 '20 at 19:11
  • 1
    Actually the correct notation of your try is `[user[0]][user[1]][user[2]]` (you should use bracket notation), but you will still get `undefined`, despite the fact, there is no value for the property that you looking for. – SMAKSS Jun 28 '20 at 19:12
  • @slappy tnx . I have **req** object .I think I could use something like this req.[user[1]].[user[2]] – Babak Abadkheir Jun 28 '20 at 19:17
  • 1
    That version would work when the first `req` is hard coded or a known object reference – charlietfl Jun 28 '20 at 19:19
  • Yes, you could do that, except you'd remove the dots. `req[user[1]][user[2]] ` That's fine if you always know how many items will be in the path. But why did you accept an answer below that doesn't do what you describe? –  Jun 28 '20 at 20:38

4 Answers4

2

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);
naveen
  • 53,448
  • 46
  • 161
  • 251
1

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));
Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43
1

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.

maioman
  • 18,154
  • 4
  • 36
  • 42
-2

You can do it like this:

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

userSplitted.forEach(key=>{o=o[key]={}});
N.Tasikj
  • 366
  • 1
  • 4
  • 2
    The title does sound like they want to create the object structure, but reading the question, it appears that they actually want to retrieve the value from an existing object structure. –  Jun 28 '20 at 19:15