2017-09-20 115 views
-1

我想实现这样的事情:字符串转换为对象路径

let database = { 
    foo: { 
    bar: {} 
    } 
} 

deepValue(database, "foo/bar/hello") = "world" 

console.log(database) 
// database: { 
// foo: { 
//  bar: { 
//  hello: "world" 
//  } 
// } 
// } 

所以deepValue在给定的路径的对象返回的地方,这样我就可以写了。有没有什么可能在ES6中,ES7可以帮助我解决这个问题?或者有没有一种从字符串生成对象路径的好方法?

回答:

确认,得到了关闭之前,我可以张贴。这里:jsfiddle.net/6bb1Lq6k - Jamiec

+0

'String.prototype.split' +'Array.prototype.forEach' – Mouser

+0

如果您使用点,你可以永远eval()它 –

+1

请*不要*使用'eval'。没有必要!你也说过你想“用给定的路径返回一个对象的值”,但是它看起来像你正在试图*写*值而不是*读*。或者你想这样做? – Jamiec

回答

-2

该实施例提供了对上述问题的基本解决。它将其分解为核心。然而,解决方案可能是可怕的,应该被视为概念验证,并且有许多方法可以打破这一点。有更好的方法来维护你的代码。请参阅覆盖这种方式尤为明显重复的条目:Convert JavaScript string in dot notation into an object reference

基于阵列的

let database = { 
 
    foo: { 
 
    bar: {} 
 
    } 
 
} 
 

 
//changed assignment to argument, since this will fail with invalid left hand assignment. 
 
deepValue(database, "foo/bar/hello", "world"); 
 

 
function deepValue(dbase, stringValue, val) 
 
{ 
 
var obj = dbase; //start the chain at base object 
 

 
//split the string based upon the slashes. 
 
//loop the array with forEach 
 
stringValue.split("/").forEach(function(value, index, arr){ 
 
    
 
    //if searched value does not exist, create 
 
    if (!obj[value]) 
 
    { 
 
    obj[value] = {}; //we use bracket notation, eliminating the need for eval. 
 
    } 
 
    obj = obj[value]; //assign the current property as newest in the chain. 
 
    if (index == arr.length-1 && val) 
 
    { 
 
    obj[value] = val; //if object reaches the end of the chain and there is a val set, assign it. We check the index against the array's length. 
 
    } 
 
}); //array from split 
 

 
} 
 

 
console.log(database)