NaN When trying to print json values - javascript

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

Related

How to extract data value that is nested inside an array

I am just trying to figure out why when trying to grab a value through the dot notation, it is giving me undefined error. Please see below for what I mean.
I am trying to extract the value from the nested object in the headline color array:
If we can assume that el.selectgroup1 is equal to some string value "[{name: 'Off White', value: 'off-white'}]". then we can deduce that el.selectgroup1[0] is equal to "[". which would not be valid JSON within JSON.parse("[").
Try something like JSON.parse(el.selectgroup1)[0].value

How to parse the following json string into an object?

var jsonString = '{"DeviceId":3,"results":{"1":"[{\"x\":513,\"y\":565,\"width\":175,\"hight\":208}]"}}';
var message = JSON.parse(jsonString);
I got an error saying Unexpected token u in JSON at position 0
at JSON.parse.
Could you please guide me what's wrong?
THanks in advance!
At the last few characters looks wrong. The :212 has no sense as the value (that long array) for key "1" was already set, so that later :212 looks weird
Also enclosing it in single quotes it makes that all be like a huge string, and not as an array structure.
See Results key as value contains a sub array which contain "1" key which as value contains a string enclosing another json array (but escaped as plain string, so no structurally accesible for the main object . But that string if post -processed the :212 is paired to what? , no key, no comma neighter , to the precedent whole array which already was the value, not the key?. Anyway weird.
In your JSON string, there is wrong something with ":212", as it's not valid JSON, because it doesn't have any property that it's mapping the value for. For example, you are mapping values for width and height with properties keys. But for "212", there is no property.
Here is the above JSON formatted:
var jsonString = '{"DeviceId":"3","results":{"1":"[{\\"x\\":513,\\"y\\":565,\\"width\\":175,\\"hight\\":208}]"}}'
var message = JSON.parse(jsonString);
If you want to format the results, you can do to it, there is no error on it:
JSON.parse(message.results['1'])
Here is the JS Bin link for above code: https://jsbin.com/fiyeyet/edit?js,console
Just an advice
Professional code is all about proper spacing, proper identation , proper commenting, don't try to write down all within one single line, structure it VISUALLY nice to see nice to read nice to comprehend, and you will be approved in most jobs.
Hint: declare a normal array/object , convert it to json string using the proper function, then use the string variable returned by the function to test your code or whatever doing. That way, you can write down in the source really nice the structure.

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}

Acessing Object Elements

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

Categories

Resources