javascript对象值的动态深度访问
Dynamic deep access of javascript object values
我有一个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]);
这是一个小提琴演示。
相关文章:
- 访问布局信息是否也会导致浏览器重排
- Javascript,访问一个主要对象模块模式中的每个对象
- 如何访问声音管理器2创建的声音对象
- 在Twitter上用ie9中的空白src访问iframe的contentWindow
- JavaScript Pub/Sub属性访问问题
- 从JavaScript访问struts操作中的属性
- 是否可以从父类访问子类的属性
- 如何访问fastOpt.js
- 访问JSON对象内部的数组元素
- 从模块内部访问Express装载路径
- 难以访问的JS环境中的语法错误
- javascript对象值的动态深度访问
- 如何访问Vue.js中深度嵌套的子组件中的数据
- 如何访问深度嵌套的 JSON 对象中的项目
- 通过深度索引访问数组元素
- 从深度嵌套的组件访问redux分派
- 访问深度嵌套图像
- 遍历json并访问二维深度
- Javascript:解析时深度对象中的访问函数
- 使用Rivets.js和Backbone深度模型绑定和访问嵌套元素