2015-09-26 50 views
0

我刚刚开始使用JavaScript并想问一个问题(显然是:P) 我已经写了两种方法,一种是根据数据路径(数据路径是对象内的结构,如下所示:“object.subObject.anotherSubObject.property”),另一个基于数据路径将值设置为对象。设置和检索javascript对象的值

下面是代码编写的打字稿:

public getValueFromObject(object:any, path:string|string[], thisArg:any = null):any { 
    thisArg = thisArg == null ? this : thisArg; 
    var value:any = null; 
    if (object == null || object == undefined || object == "undefined") 
     return value; 
    if (path == null || path == undefined || path == "undefined" || path == "") 
     return value; 
    if (typeof path == "string" && !Array.isArray(path)) { 
     path = (<string>path).split("."); 
    } 
    var currPath:string = path[0]; 
    if (path.length > 1 && object.hasOwnProperty(currPath)) { 
     value = thisArg.getValueFromObject(object[currPath], path.slice(1), thisArg); 
    } 
    else if (object.hasOwnProperty(currPath)) { 
     value = object[currPath]; 
    } 
    return value; 
} 

private setValueToObject(dataObject:any, value:any, dataPath:string|string[], thisArg:any = null):any { 
    thisArg = thisArg == null ? this : thisArg; 
    if (dataObject == null || dataObject == undefined || dataObject == "undefined") 
     return null; 
    if (dataPath == null || dataPath == undefined || dataPath == "undefined" || dataPath == "") 
     return null; 
    if (typeof dataPath == "string" && !Array.isArray(dataPath)) { 
     dataPath = (<string>dataPath).split("."); 
    } 
    var currPath:string = dataPath[0]; 
    if (dataPath.length > 1) { 
     if (!dataObject.hasOwnProperty(currPath)) { 
      dataObject[currPath] = {}; 
     } 
     dataObject[currPath] = thisArg.setValueToObject(dataObject[currPath], value, dataPath.slice(1), thisArg); 
    } 
    else { 
     dataObject[currPath] = value; 
    } 
    return dataObject; 
} 

现在,我想知道,这是一个很好的书面JavaScript代码,以及是否有可能做我想同样的事情,任何库实现?也许lodash?如果有人提供示例代码,我们将非常感激。

预先感谢您。

+1

我不得不问,为什么你需要得到和设置这样的对象的价值,当你可以正常地做它 – Jesse

+0

那么,什么是“正常”的方式:D 并回答,我需要当我向后端发送请求时有一定的对象结构。这是我能想到的最方便的“通用”方式。只需传递一组字符串(或一个字符串)和一个值。 – Franz1986

+0

要在评论中提供答案,因为评论中的代码是皱眉脸的情况 – Jesse

回答

-1

对象与JavaScript是相当可塑的,因为它是。

启动一个对象

var myobj = { 
    var1: 'hello' 
} 

获取VAR1

console.log(myobj.var1) // 'hello' 

集VAR1

myobj.var1 = 'world' 

获取VAR1再次

console.log(myobj.var1) // 'world' 

整合所有输出的“Hello World”到控制台

var myobj = { var1: 'hello' }; 
console.log(myobj.var1); 
myobj.var1 = 'world'; 
console.log(myobj.var1); 

除此之外,你的代码看起来很确定。有很多方法可以让猫变皮肤,绝不是一种比其他方式更好的方式。写出像你一样的好作法是件好事。尽管如此,你也应该注意更快的方法来改善你的代码。

+0

好吧,问题在于,我并不总是知道对象结构会是什么样子。所以我使用这些“通用”函数从字符串路径创建对象。我希望我有道理。 – Franz1986

+0

当然,男人,听起来不错。最适合你的是最适合你的东西。 – Jesse

+0

“你也应该知道更快的方法来改善你的代码在生产中。” 你可以分享一些想法吗?或者,也许我可以指点一些提示和技巧来编写产品价值代码的JavaScript资源? 我想学习,并在这个变得更好,因为我的背景主要是C#,AS3,Java和C++ :) – Franz1986