[英]Accessing Properties in object using bracket notation
I'm using an ajax call through javascript and returning json. 我正在通过javascript使用ajax调用并返回json。
I'm accessing the data using bracket notation because the object name had spaces, so I couldn't use dot notation. 我使用括号表示法访问数据,因为对象名称中包含空格,因此无法使用点表示法。
This is the success function of my ajax call(not putting in the whole ajax call because of the API key). 这是我的ajax调用的成功功能(由于API密钥而没有放入整个ajax调用)。
success: function(data){
console.log(data);
console.log(data['Time Series (1min)']);
},
I want the last property in the long list of properties in the "Time Series (1min)" object. 我想要“时间序列(1分钟)”对象中一长串属性中的最后一个属性。 I can't call it by key/property name as every minute, the property name changes (the data is minute-by-minute). 我无法通过键/属性名称来称呼它,因为属性每隔分钟就会更改一次(数据是一分钟一分钟的)。 I haven't found anything so far to help me online. 到目前为止,我还没有找到任何可以帮助我上网的信息。 I've tried .last() but dot notation and brackets don't seem to jive. 我已经尝试过.last(),但是点符号和方括号似乎并不有趣。 Any ideas? 有任何想法吗?
Once you got the data: 获得数据后:
const series = data['Time Series (1min)'];
Just take all the keys and get the one with the highest timestamp: 只需获取所有密钥,即可获得时间戳最高的密钥:
const last = Object.keys(series).reduce((a, b) => a > b ? a : b);
Now that weve got the highest key, its easy: 现在我们有了最高的钥匙,这很容易:
console.log(series[last]);
All that is necessary cause object key order is not guaranteed, so you may switch over to using an array or a Map. 不能保证对象键顺序的所有必要操作,因此您可以切换到使用数组或Map。
I assume that you simply want to get value of the last property of the object. 我假设您只是想获取对象的最后一个属性的值。 (Based on this topic, object properties are sorted) (基于该主题,对对象属性进行了排序)
What about simpler: 那么简单些:
data[Object.keys(data).pop()]
//Edit: //编辑:
First of all you want to get "Time Series" property (which changes minute by minute), so maybe you want something like this: 首先,您要获取“时间序列”属性(每分钟更改一次),所以也许您需要这样的东西:
data[Object.keys(data).find(key => key.match(/Time Series \(\d+min\)/))]
This will get value of time zone property in your scheme (object with dates). 这将获得您方案中时区属性的值(带有日期的对象)。 And - as I see - data that you receive is sorted by datetime, you can get object you are interested in by running code I've written in not edited post. 而且-正如我所看到的-您收到的数据是按日期时间排序的,您可以通过运行我在未经编辑的帖子中编写的代码来获取您感兴趣的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.