我有一个像这样的字符串:
let user = "req.user.role"
有什么方法可以将其转换为嵌套对象,以用于其他这样的值?
let converted_string = req.user.role
我知道我可以使用 user.split(“。”)
拆分用户
我的想象力:
let user = "req.user.role".split(".")
let converted_string = user[0].user[1].user[2]
我找到了与我的问题最接近的答案:Create nested object from query string in Javascript
答案 0 :(得分:2)
尝试一下
let user = "req.user.role";
let userObj = user.split('.').reduceRight((obj, next) => ({
[next]: obj
}), {});
console.log(userObj);
或者,对于旧的浏览器
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);
答案 1 :(得分:1)
函数getvalue()
将返回给定全局变量的嵌套属性:
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));
答案 2 :(得分:1)
我将为此开枪
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)
此函数将遍历传入的对象达到所提供string.split“。”的整个长度。列表返回值或未定义。
答案 3 :(得分:-2)
您可以这样做:
if(strcmp(e.name,empname) == 0)
{
printf("\nEnter new name,sex,address,designation,age,salary,employee ID ");
scanf("%s %s %s %s %d %.2f %d",e.name,e.sex,e.adrs,e.dsgn,&e.age,&e.slry,&e.empID);
fseek(fptr,-recsize,SEEK_CUR);
fwrite(&e,recsize,1,fptr);
break;
}