Acessing Object Elements - javascript

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"]

Related

Accessing Properties in object using bracket notation

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.

Access element of dictionary in pug/jade

If I have a dictionary like:
x = {"A" : 1, "B" : 2 }
And I pass this dictionary into the pug file, how can I access a specific key value without iterating through all the elements in the dictionary?
For ex. x[A]
The only way I can think of right now is to iterate through the elements:
for key, val in x
And then have an if conditional in there that displays val when key equals A.
Am I missing something obvious here?
If you passes x dictionary to your .pug file you can simply show the key 1 of this dictionary using ${x.A}, same as in normal javascript.
Be sure to add back-tick between the expression.
every Javascript object is an associative array which is the most general sort of array you can invent - sometimes this is called a hash or map structure or a dictionary object.
An associative array is simply a set of key value pairs.
The value is stored in association with its key and if you provide the key the array will return the value.
This is all an associative array is and the name comes from the association between the key and the value. The key is a sort of generalized address that can be used to retrieve the stored value.
For example:
array={key1: 'value1',key2:'value2'};
creates an object called array with two keys and two values which in this case happen to be two constant strings.
Notice that the value stored can be any JavaScript object and in this example it is probably better to think of storing two string objects rather two string literals.
The key can be either an identifier, a string or a number but more about the difference in the key type as we progress.
You can retrieve a value via it key using array notation:
console.log(array['key2']);
Which displays the string value2. If you try and access a key that doesn't exist then you get the result undefined.
As the associative array is used to as the basis of the JavaScript object there is an alternative way to access a value that makes the key look like a property. That is you can access the value using "property syntax" as in:
console.log(array.key2);
So in jade/pug if you pass the x it will show you the similar result like in js. In your case it would be something like that:
${x["A"]} or ${x.A}

insert an object as identic document into mongo

I have an object that i like to store into mongo. My issue is that i want to store the object's attributes as fields of the document, and not the whole object as a single field.
obj ={attA:x, attB:y} ;
MyCol.insert({obj});
After inserting the object I get this:
{_id:xxxx, obj:{attA, attB}}
Rather I'm looking for this result
{_id:xxx, attA:x, attB:y}
I tried with a JSON.stringify but didn't work. What am i missing?
Do it in this way:
MyCol.insert(obj);
Note, in ES6 creating object using syntax {obj}, is the same as {obj:obj}.

NaN When trying to print json values

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"]

How to get data from this objects num property using the name property as a selector

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.

Categories

Resources