javascript对象值的动态深度访问

Dynamic deep access of javascript object values

本文关键字:深度 访问 动态 对象 javascript      更新时间:2023-09-26

我有一个Java脚本对象,我正试图从中动态访问特定值,并将其更改为

我的目标:

myJson =  {
            "id" : "http://**********",
            "$schema": "http://json-schema.org/draft-04/schema",
            "type" : "object",
            "properties":{
            "AddressLine1" :{"type":"string" , "maxLength":62},
            "AddressLine2" :{"type":"string" , "maxLength":62},
            "city" :{"type":"string" , "maxLength":62},
            "state" :{"type":"string" , "maxLength":5}
        },
        "required": ["AddressLine1", "city"]
        }

例如,如果我需要根据给定的"路径"动态访问状态对象中的maxLength

path = "$.properties.state.maxLength";

因此,基于我得到的变量"路径",我必须访问基于路径的值并对其进行编辑

完整代码:

var sample = function (){

    var myJson = {
        "id" : "http://application.nw.com/address",
        "$schema": "http://json-schema.org/draft-04/schema",
        "type" : "object",
        "properties":{
        "AddressLine1" :{"type":"string" , "maxLength":62},
        "AddressLine2" :{"type":"string" , "maxLength":62},
        "city" :{"type":"string" , "maxLength":62},
        "state" :{"type":"string" , "maxLength":5}
    },
    "required": ["AddressLine1", "city"]
    }
    // I get the path from an external source.
    path = "$.properties.state.maxLength";
    path = path.substring('$.'.length);
    console.log(path);          // log = properties.state.maxLength
    console.log(myJson.properties.state.maxLength);        // log 5
    console.log(myJson.path);                      // log undefined

}

我是一个新手,如果我做了一些非常愚蠢的事情,请帮忙并鼓励我。

感谢

如果有任何错误,请随时编辑

您需要解析路径才能访问属性。

因为path是一个变量,所以myJson.path没有意义。dot表示法表示一个特性。

因为需要根据变量的内容动态访问属性,所以需要使用bracket表示法。对象中的每个深度级别都需要自己的括号。

console.log(myJson) --> the object
console.log(myJson["properties"]  --> the properties property of the object
console.log(myJson["properties"]["state"] --> the state property of the properties property

使用括号表示法,可以将path变量解析为其组成部分:

var p1 = "properties";
var p2 = "states";
var p3 = "maxLength";
console.log(myJson[p1][p2][p3]);

这是一个小提琴演示。