获取Javascript嵌套对象属性完整地址作为字符串

获取Javascript嵌套对象属性完整地址作为字符串,javascript,object,dom,Javascript,Object,Dom,我想将DOM元素ID设置为嵌套对象属性的完整地址。如何将对象属性地址转换为字符串 我欢迎另一种命名DOM元素的方法,这样就可以清楚地知道它引用的是什么对象属性 var myBowtie = {"Hazard":{"Name":"Hydrocarbons under Pressure"}, "TopEvent":{"Name":"Loss of Containment"}, "Cause1": {

我想将DOM元素ID设置为嵌套对象属性的完整地址。如何将对象属性地址转换为字符串

我欢迎另一种命名DOM元素的方法,这样就可以清楚地知道它引用的是什么对象属性

var myBowtie = {"Hazard":{"Name":"Hydrocarbons under Pressure"},
                "TopEvent":{"Name":"Loss of Containment"},
                "Cause1": {
                  "Name":"Cause 1",
                  "Barrier1": {
                    "Name":"Barrier 1",
                    "Type":null,
                    "Health":null,
                    "DegFactor1":{
                      "Name":null,
                      "Barrier1": {
                        "Name":null,
                        "Health":null
                        }
                     },
                    },
                },
                "Cause2": {
                  "Name":"Cause 2",
                  "Barrier0": {
                    "Name":"New Barrier 1",
                    "Type":null,
                    "Health":null,
                    "DegFactor1":{
                      "Name":null,
                      "Barrier1": {
                        "Name":null,
                        "Health":null
                        }
                     },
                    },
                },
                "Consequence2": {
                  "Name":"Consequence 2",
                  "Barrier1": {
                    "Name":"New Barrier 1",
                    "Type":null,
                    "Health":null,
                    "DegFactor1":{
                      "Name":null,
                      "Barrier1": {
                        "Name":null,
                        "Health":null
                        }
                     },
                    },
                },
             };

displayBowtie("Barrier",myBowtie.Cause1);

function displayBowtie(elementType,objectName){
    if (Object.entries(objectName).length > 0){ //ensure object has properties
    const Entries = Object.entries(objectName);
      for (const entry of Entries){ //loop through properties
        if (entry[0].includes(elementType)){ //loop through each property that matches the name
          //would like to have a string = "myBowtie.Cause1.Barrier1". I can then set this to a DOM element ID for accessing information later 
        }
      }
    }

}

您的json无效,验证后应如下所示,然后您可以通过
[]

如果您确定名称是唯一的,那么可以通过
myBowtie.Cause1.Barrier1.name将其用作html对象的
id

让我的领结={
“危险”:{
“名称”:“受压碳氢化合物”
},
“TopEvent”:{
“名称”:“失去控制”
},
“原因1”:{
“名称”:“原因1”,
“Barrier1”:{
“名称”:“屏障1”,
“类型”:空,
“健康”:空,
“DegFactor1”:{
“名称”:空,
“Barrier1”:{
“名称”:空,
“健康”:空
}
},
},
},
“原因2”:{
“名称”:“原因2”,
“Barrier0”:{
“名称”:“新屏障1”,
“类型”:空,
“健康”:空,
“DegFactor1”:{
“名称”:空,
“Barrier1”:{
“名称”:空,
“健康”:空
}
},
},
},
“结果2”:{
“名称”:“结果2”,
“Barrier1”:{
“名称”:“新屏障1”,
“类型”:空,
“健康”:空,
“DegFactor1”:{
“名称”:空,
“Barrier1”:{
“名称”:空,
“健康”:空
}
},
},
},
};
让cause1=myBowtie.cause1
如果(导致1.拥有自己的财产(“障碍物”)){
log(“对象-”+JSON.stringify(id,null,4))
log(“对象名-”+id.name)
}
否则{
console.log(“myBowtie.Cause1不包含Barrier1属性”);

}
以下脚本应该能够帮助您解决问题

var varFind = function (predicate, object, layers) {
    //errors
    if (typeof(predicate) !== "function") {
        throw "First agrument is not a function. Example is (key, obj, path) => obj[key] == 234095843.";
    }
    if (typeof(object) !== "string") {
        throw "Second agrument is not a string. Example is \"myObj\".";
    }
    if (typeof(layers) !== "number" && layers !== undefined) {
        throw "Third agrument is not a number. Example is 15.";
    }
    var newEval = function (str) {
        try{
            return new Function("return " + str + ";")();
        } catch (e) {
            return null;
        }
    }
    //where result will be stored
    const results = [];
    //to prevent cors error
    const isElement = function (element) {
        try{
            return element instanceof Element || element instanceof HTMLDocument;
        } catch(e){
            return false;
        }   
    }
    //path finding function
    const varSearch = function (obj, path, cyclicDetect, layers) {
        //initial set up
        if(typeof(path) == "undefined") {
            path = [
                (newEval(object) || window) === window ? "window" : object
            ];
            cyclicDetect = [];
        }
        //looping through object
        for (var key of Object.keys(obj)) {
            //to prevent errors
            try {
                //layers is used more in lag reduction
                layers = typeof(layers) == "number" ? layers : Infinity;
                //pushing current key to path
                path.push(key);
                //if matches predicate
                if(predicate(key, obj, path) === true) {
                    //cloning path for modification
                    var editedPath = [...path];
                    //putting in propper formatt
                    for (var i in path) {
                        if (i != 0) {
                            editedPath[i] = "['" + editedPath[i].replace(/'/g, "\\'") + "']";
                        }
                    }
                    //pushing result to results
                    results.push(editedPath.join(""));
                }
                //to help with cyclic detection
                var isCyclic = false;
                //for easier access
                const o = obj[key];
                //testing if element to prevent cors error and if it is an object
                if (o && typeof o === "object" && !isElement(o) && layers != 0) {
                    //pushing object to cyclic detect
                    cyclicDetect.push(obj);
                    for(var i in cyclicDetect) {
                        //checking if cyclic
                        if(cyclicDetect[i] == o) {
                            isCyclic = true;
                        }
                    }
                    //recursion!
                    if (!isCyclic) {
                        varSearch(o, path, cyclicDetect, layers - 1);
                    }
                    //popping cyclicDetect for future objects not in that recursion
                    cyclicDetect.pop(obj);
                }
                //popping path for the next possible path
                path.pop();
            } catch (e) {}
        }
    }
    //getting results
    varSearch(newEval(object) || window, undefined, undefined, layers)
    return results;
}
这将提供更多查找选项,提供所有符合条件的对象,并绕过循环链接

使用示例:

var document.getElementById("IdHere").innerHTML = varFind((key, obj, path) => key === "Barrier1", "myBowtie")[0];
您案例中的输出:

myBowtie['Cause1']['Barrier1']
//the reason it is using the `[]` notation is because that the object supports more characters when calling it.

^^快乐编码