[英]Value substitution while accessing nested json object
This is my json object 这是我的json对象
{
"a1": {
"b1": {
"name": "Tim",
"status": "Completed"
}
"c1" {
"field1": "name",
"field2": "status"
}
}
I need to access the value Tim by getting the field key within c1. 我需要通过获取c1内的字段键来访问值Tim。 For example, I need to get the value of a1.c1.field1 which gives me the value name1 , then I need to access the value tim by a1.b1.(value of a1.c1.field1) I do not know how to do this.
例如,我需要获取a1.c1.field1的值,该值将给我提供值name1,然后我需要通过a1.b1。(a1.c1.field1的值)访问值tim。做这个。 Can someone give the possible ways to accomplish this?
有人可以给出实现此目的的可能方法吗?
Your JSON is a little off, so it's corrected below. 您的JSON有点差了,因此在下面已更正。 This is an example of how to retrieve the value of field1 in the c1 object (in the a1 object)
这是一个如何在c1对象(在a1对象中)中检索field1值的示例。
$(document).ready(function () {
var json = {
"a1":
{
"b1":
{
"name": "Tim",
"status": "Completed"
},
"c1":
{
"field1": "name",
"field2": "status"
}
}
};
console.log(json.a1.b1.name); // returns Tim
// or
console.log(json["a1"]["b1"]["name"]); // returns Tim
});
Is this what you're looking for? 这是您要找的东西吗?
You can access using square brackets. 您可以使用方括号进行访问。 With the data you provided,
利用您提供的数据,
var data = {
"a1": {
"b1": {
"name": "Tim",
"status": "Completed"
},
"c1":{
"field1": "name",
"field2": "status"
}
}
};
You can achieve your requirement by accessing. 您可以通过访问来满足您的要求。
data.a1.b1[data.a1.c1.field1]
The obvious way is to use a1.c1.field1
as a property accessor using the bracket notation. 一种明显的方法是使用
a1.c1.field1
括号表示法将a1.c1.field1
用作属性访问器。
var obj = {
"a1": {
"b1": {
"name": "Tim",
"status": "Completed"
},
"c1": {
"field1": "name",
"field2": "status"
}
}
};
console.log(obj.a1.c1.field1); // 'name'
console.log(obj.a1.b1[obj.a1.c1.field1]); // 'Tim'
or, more legibly, 或者更清晰地
var key = obj.a1.c1.field1;
var value = obj.a1.b1[key];
console.log(value); // 'Tim'
var a1 =
{
"b1":
{
"name": "Tim",
"status": "Completed"
},
"c1":
{
"field1": "name",
"field2": "status"
}
};
console.log(a1.b1[a1.c1.field1]);
Do fix the error in your json too ;) 还要修复json中的错误;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.