当前字符串:folder1/folder2/folder3
我需要转换为:['folder1']['folder2']['folder3']
我尝试过的事情:
let folder = "folder1/folder2/folder3";
let splittedFolder = folder.split('/');
let newFolder = splittedFolder.join('[' ']');
我认为我绝对是错误的...。我想实现一种像userDB['folder1']['folder2']['folder3']
这样的想法来导航到对象并对其进行编辑。
答案 0 :(得分:1)
您可以用斜杠分隔,然后映射以用['']
括起来的每个字符串,然后再次加入:
let folder = "folder1/folder2/folder3";
const output = folder
.split('/')
.map(str => `['${str}']`)
.join('');
console.log(output);
但是除非使用eval
,否则您不能使用这样的字符串导航普通对象,而您实际上不应该使用该字符串。如果是文字代码
userDB['folder1']['folder2']['folder3']
将导致访问所需的嵌套值,然后从输入中获取,请使用reduce
:
const val = folder.split('/')
.reduce((a, key) => a[key], userDB);
或者,要处理介于两者之间的可能未定义对象:
const val = folder.split('/')
.reduce((a, key) => a !== undefined ? a[key] : undefined, userDB);