[英]Best Method to Grab Specific Keys(Properties) from Nested Object in JavaScript
What is the best method to get specific keys (ie "longName") from nested objects with this structure:从具有此结构的嵌套对象中获取特定键(即“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"
},
I have tried to console.log(routes[1]), dot notation, and other methods but I am not having any success.我尝试了 console.log(routes[1])、点符号和其他方法,但没有取得任何成功。
The structure here is an object of objects.这里的结构是一个 object 个对象。 So you can access the
longName
key-value pair in this manner: routes[14094].longName
which should return Route 1
, based on the original data.因此,您可以通过以下方式访问
longName
键值对: routes[14094].longName
应根据原始数据返回Route 1
。
If you want to get all the longName
values for each object, you can use a for loop like this:如果要获取每个 object 的所有
longName
值,可以使用这样的 for 循环:
for (const key in routes) {
console.log(routes[key].longName)
}
You need to first reference the object using the "outer" key (eg 14094), then you can use dot notation for the keys in the "inner" object.您需要先使用“外部”键(例如 14094)引用 object,然后您可以对“内部”object 中的键使用点表示法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.