I'm using an ajax call through javascript and returning 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).
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?
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.
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.
Related
I am working with AbsoluteOrientationSensor
I have an object that contains the values of the accelerometer of the phone.
The values that I need are nested inside an Symbol in the Object.
How do I access those values?
The Object Name is "message".
I have already tried this
console.log(message.__sensor__.quaternion);
But I am getting the result as "undefined".
I have never worked with the Symbol data type in JavaScript before.
The Values that I want to access are the quaternion values
This is the screenshot of the Object Structure -
Thank you for your help.
From the documentation:
Properties
OrientationSensor.quaternion: Returns a four element Array whose elements contain the components of the unit quaternion representing the device's orientation.
So:
console.log(message.quaternion);
You can also see in the screenshot that the object itself has a getter quaternion.
I have never worked with the Symbol data type in JavaScript before.
Symbols are used for various reasons as property names, but if they are used, it almost always means that you, as a consumer of the API, are not supposed to access that value directly. Instead you should use the "public" API the object provides to access this data, such as in this case.
function GetSymbol(object, name) {
const string = `Symbol(${name})`
return Object.getOwnPropertySymbols(object).find(symbol => symbol.toString() === string)
}
const __sensor__ = GetSymbol(message, "__sensor__")
console.log(message[__sensor__])
When I do
console.log(JSON.stringify(chunks1[1].data)))
This is the log:
"{\"data\":{\"0\":0.00006103515625,\"1\":0.00018310546875,\"2\":0.00018310546875,\"3\":0.0001220703125,\"4\":-0.0003662109375,\"5\":-0.000396728515625,\"6\":-0.000518798828125,\"7\":-0.00054931640625,\"8\":-0.00048828125,...
Now can I access the elements of "data"?
If I do
chunks1[1].data[0]
I get nothing. And
chunks1[1].data.1
Obviously I will get an error.
data is an object. Apart from getting the property with data.propertyName, you can also get it using an array notation, specifying the property name as a string. Like this:
chunks1[1].data['0']
#aduch makes a good point there. There is another 'data' in the output which I overlooked. The object with the numeric properties is actually a subobject, so the correct notation would be:
chunks1[1].data.data['0']
Currently, you are trying to access the elements of data as if it were an array, with numbered indexes, e.g. chunks1[1].data[0].
Instead, because data is an object, you should be using a string index: chunks1[1].data["0"].
And, because in your console.log example, chunks1[1].data is an object containing data as a key, your final accessing scheme should look like:
chunks1[1].data.data["0"]
I was trying to parse a json which I got as a response of querying connections in linked in.
when I do JSON.stringify in an array as a whole I can see values in console.log
but when I try to take individual values inside array I get NaN.
Why can I not get Individual values when I can see the array as a whole.
here is the code
var response = jQuery.parseJSON(data);
var person = response.person[0];
in the above code I am getting data as a response of an ajax call
person is an array inside, I can stringify the array as a whole.
if I do
console.log(JSON.stringify(person));
I will get
{"id":"someId","first-name":"someName","last-name":"someName, DMC-E, DMC-D","picture-url":"https://soempicture"}
but When I try to take it individually
console.log(person.first-name);
I get NaN , and trying to strigify it results in Null
am I missing something, should I do string split to get the values?
Thank you
You can't access the first-name property using period notation, as the name contains a dash.
The code will be interpreted as person.first - name, i.e. the person.first property minus the name variable.
Use the bracket notation for any property where the name can't be an identifier:
console.log(person['first-name']);
To access a key that contains characters that cannot appear in an identifier (-), use brackets, i.e.:
person["first-name"]
I am trying to find the value of the num property of this object using the name property to select the right object from the hashtagsl array; so I get the right num value. I need to do this knowing only what the name in the element and userid are. The end goal is variable equal to the value of num in the specific object. Here is the code creating the object to show the structure of it. Thanks in advanced.
All code shown is server side.
Meteor.users.update({"_id": this.userId},{"$push":{"profile.hashtagsl": {name: newhashtag, num: 1}}})
edit
Here it is updating incing the num property. I need to get the value of num instead of updating it.
Meteor.users.update({"_id": this.userId, "profile.hashtagsl.name":hashi},{"$inc":{"profile.hashtagsl.$.num":1}});
I think this should do it:
Meteor.users.findOne({'profile.hashtags1.name': somehashtag}).profile.hashtags1[index].num;
As you can see, accessing nested properties in a MongoDB query can be done through the dot notation. Using findOne returns an object with a similar structure, and you can access the num property as you would any other javascript object.
Edit: I forgot to add that you have to specify an index for the hashtags, since the user document has an array of hashtags.
I have an IndexedDB of changes. I add an item like this, and then log the result to check the key has been created successfully:
_this._idb.add('steps', step).done(function (items) {
var item = items[0];
_logger.log("ADDED STEP", { id: item.__id__, step: item }, "CT");
});
The output from this is as expected:
...as you can see, the id has been added to the object when it is stored.
However, when I query the db to getback a list of objects, using this code:
this._idb.steps.query('timestamp').bound(start, end).execute().done(function (results) {
_logger.log("Results", results, "CT");
}
I don't get the id as part of the object that is returned:
... and the lack of id makes updating and deleting impossible.
How can I get the id of the item when I query indexed db using db.js - or am I approaching this in the wrong way, and is there something else I should be doing?
(Note: I'm using TypeScript to compile the JS, but I don't think that's especially relevant to this question)
This is expected behaviour, you're only going to get the __id__ property if you don't define a keyPath in your db schema.
Because there's no keyPath defined the value is not associated with it in indexeddb, it's only added to the resulting object after it has been added, because at that point in time we know the auto-incremented value that IndexedDB has assigned to it.
Since the value isn't really part of the object I don't have any way to assign it to the object when it comes out during a query, maybe I could use the position in the array but that's more likely to be wrong than right.
If you want the ID to be persisted against the object then you need to define a keyPath as part of the object store schema and the property will be added to the resulting object and available and it will be on the object returned from a query.
Disclaimer - I wrote db.js
Looking at the source, __id__ is only defined when your keyPath is null in the add() method. From what I'm seeing, you'll never see this in a query() response.
In IDB null keyPaths are allowed only when using auto-incrementing ("out-of-line") keys. So if you're getting the object back, it should have an auto-incrementing key on it or some other keyPath.
The __ prefix in JavaScript usually means the developer intended it to be a "private" property. I'm guessing this is for internal use and you shouldn't be counting on this in your application code.
Consider using explicit, so-called "in-line" keys on your object store.
The goal of db.js is easy and simple to use. Your is advanced use case.