我剛剛開始使用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