从 JavaScript 中的嵌套对象获取特定键(属性)的最佳方法
从具有这种结构的嵌套对象中获取特定键(即“longName”)的最佳方法是什么:
const routes = {
"14094": {
"routeId": 14094,
"shortName": "2",
"longName": "Route 1"
},
"14095": {
"routeId": 14095,
"shortName": "7",
"longName": "Route 2"
},
"14096": {
"routeId": 14096,
"shortName": "42",
"longName": "Route 3"
},
"14097": {
"routeId": 14097,
"shortName": "57",
"longName": "Route 4"
},
我尝试过 console.log(routes[1])、点符号和其他方法,但没有取得任何成功。
What is the best method to get specific keys (i.e. "longName") from nested objects with this structure:
const routes = {
"14094": {
"routeId": 14094,
"shortName": "2",
"longName": "Route 1"
},
"14095": {
"routeId": 14095,
"shortName": "7",
"longName": "Route 2"
},
"14096": {
"routeId": 14096,
"shortName": "42",
"longName": "Route 3"
},
"14097": {
"routeId": 14097,
"shortName": "57",
"longName": "Route 4"
},
I have tried to console.log(routes[1]), dot notation, and other methods but I am not having any success.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里的结构是对象的对象。因此,您可以通过以下方式访问
longName
键值对:routes[14094].longName
,它应返回Route 1
,基于原始数据。如果你想获取每个对象的所有
longName
值,你可以使用这样的for循环:你需要首先使用“outer”键(例如14094)引用该对象,然后你可以对“内部”对象中的键使用点表示法。
The structure here is an object of objects. So you can access the
longName
key-value pair in this manner:routes[14094].longName
which should returnRoute 1
, based on the original data.If you want to get all the
longName
values for each object, you can use a for loop like this:You need to first reference the object using the "outer" key (e.g. 14094), then you can use dot notation for the keys in the "inner" object.