我刚刚开始使用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?如果有人提供示例代码,我们将非常感激。
预先感谢您。
我不得不问,为什么你需要得到和设置这样的对象的价值,当你可以正常地做它 – Jesse
那么,什么是“正常”的方式:D 并回答,我需要当我向后端发送请求时有一定的对象结构。这是我能想到的最方便的“通用”方式。只需传递一组字符串(或一个字符串)和一个值。 – Franz1986
要在评论中提供答案,因为评论中的代码是皱眉脸的情况 – Jesse