J.G.Sable
J.G.Sable

Reputation: 1388

Accessing Properties in object using bracket notation

I'm using an ajax call through javascript and returning json.

enter image description here

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).

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. 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. Any ideas?

Upvotes: 0

Views: 532

Answers (2)

Piotr Szyma
Piotr Szyma

Reputation: 199

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.

Upvotes: 0

Jonas Wilms
Jonas Wilms

Reputation: 138267

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.

Upvotes: 3

Related Questions