Javascript 如果名称包含点,如何获取 JSON 对象值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2577172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get JSON objects value if its name contains dots?
提问by Nik Sumeiko
I have a very simple JSON array (please focus on "points.bean.pointsBase"object):
我有一个非常简单的 JSON 数组(请关注“points.bean.pointsBase”对象):
var mydata =
{"list":
[
{"points.bean.pointsBase":
[
{"time": 2000, "caption":"caption text", duration: 5000},
{"time": 6000, "caption":"caption text", duration: 3000}
]
}
]
};
// Usually we make smth like this to get the value:
var smth = mydata.list[0].points.bean.pointsBase[0].time;
alert(smth); // should display 2000
But, unfortunately, it does display nothing.
When I change "points.bean.pointsBase"to smth without dots in it's name - everything works!
However, I can't change this name to anything else without dots, but I need to get a value?!
Is there any options to get it?
但是,不幸的是,它没有显示任何内容。
当我将“points.bean.pointsBase”更改为名称中没有点的 smth 时 - 一切正常!
但是,我不能将此名称更改为没有点的任何其他名称,但我需要获取一个值?!
有没有办法得到它?
回答by Russell Leggett
What you want is:
你想要的是:
var smth = mydata.list[0]["points.bean.pointsBase"][0].time;
In JavaScript, any field you can access using the . operator, you can access using [] with a string version of the field name.
在 JavaScript 中,您可以使用 . 运算符,您可以使用 [] 和字段名称的字符串版本进行访问。
回答by z33m
in javascript, object properties can be accessed with . operator or with associative array indexing using []. ie. object.propertyis equivalent to object["property"]
在 javascript 中,可以使用 . 运算符或使用 [] 的关联数组索引。IE。object.property相当于object["property"]
this should do the trick
这应该可以解决问题
var smth = mydata.list[0]["points.bean.pointsBase"][0].time;
回答by TK.
Try ["points.bean.pointsBase"]
尝试 ["points.bean.pointsBase"]
回答by Vikas s kumar
If json object key/name contains dot......! like
如果 json 对象键/名称包含点......!喜欢
var myJson = {"my.name":"vikas","my.age":27}
Than you can access like
比你可以访问
myJson["my.name"]
myJson["my.age"]
回答by Ashutosh Ranjan
Just to make use of updated solution try using lodash utility https://lodash.com/docs#get
只是为了利用更新的解决方案尝试使用 lodash 实用程序 https://lodash.com/docs#get

