设置和检索javascript对象的值

Setting and retrieveing value from javascript objects

本文关键字:对象 javascript 检索 设置      更新时间:2023-09-26

我刚刚开始使用javascript,想问一个问题(显然:p)我写了两个方法,一个是从对象中获取值,基于它的数据路径(数据路径是一个对象中的结构,像这样:"object. subobject . anothersubobject .property"),另一个基于数据路径为对象设置值。

下面是用typescript写的代码:

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 ?如果有人能提供一个示例代码,我将非常感激。

提前感谢。

对象是相当可塑的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);

除此之外,你的代码看起来还不错。"剥猫皮的方法不止一种",而且在为乐趣而编程时,没有哪一种方法比另一种更好。像你那样写东西是很好的练习。您还应该知道在生产环境中改进代码的更快的方法。