Javascript MongoDB/JS从字符串创建对象键
我有一个字符串,例如: key=person.name.first 有没有可能把它转换成Javascript MongoDB/JS从字符串创建对象键,javascript,mongodb,Javascript,Mongodb,我有一个字符串,例如: key=person.name.first 有没有可能把它转换成 { person: { name: { first: '????' } } } 您可以编写一个小的递归实用程序函数来在java脚本中实现这一点 var key = "person.name.first".split("\."); var obj = {}; function create(o,index){ if(index
{
person: {
name: {
first: '????'
}
}
}
您可以编写一个小的递归实用程序函数来在java脚本中实现这一点
var key = "person.name.first".split("\.");
var obj = {};
function create(o,index){
if(index > key.length-1) return;
o[key[index]] = {};
index++;
create(o[key[index-1]],index);
}
// Call the recursive function:
create(obj,0);
然后可以将该值设置为:person.name.first=value
如果要设置值,或动态设置每个字段(如数组或对象)的类型,可以使用映射数组,该数组保存每个字段的类型,并可在创建过程中读取