Accessing response data using Angular.js with numerical named field - javascript

My response object has a field called "50", so right now I'm trying to access and save that data doing something like this:
var thing = $scope.data.array[0].50;
However I'm getting an error on the console when I simply reload the page with the function not even running. When I get rid of the 50, everything is fine. There is indeed a field called "50" inside the $scope.data.array[0] and I do not have access to change the response. Is there something wrong with this because the field is called "50" and maybe JS is interrupting that as a number instead??
Also when I changed "50" to something random like "af", then I get no errors on refresh.
this doesn't work
var thing = $scope.data.array[0].50;
this works
var thing = $scope.data.array[0].af;

The following should work if your first element of the array has a property called "50".
var thing = $scope.data.array[0]["50"];
Property accessors provide access to an object's properties by using the dot notation or the bracket notation.
Syntax
object.property
object["property"]
JavaScript objects are also associative arrays (hashes). Using these you can associate a key string with a value string as shown in the example above.
The reason as to why you don't get an error when accessing $scope.data.array[0].af; is because "af" is valid identifier for a property. Dot notation only works with property names that are valid identifiers. An identifier must start with a letter, $, _ or unicode escape sequence.
For all other property names, you must use bracket notation.

Related

Unable to use Computed Property Values with Dots - Unable to Set as String - JS

Example code: https://playcode.io/757707/
Take a look at what it is logging to the console.
I am not sure if there is a way to compute property values, that have dots in the names, as valid JSON.
that third field in the objects that are printed is always:
{
dot.notation: "value"
}
In order for it to be valid JSON you need quotes around the property name if you would like to have a dot "." in the property name.
e.g. Valid JSON would look like this:
{
"dot.notation": "value"
}
It seems it's bad practice to use a dot in a property name... but there should be a way to set that property as a string explicitly so the JSON isn't invalid if I compute the property name. Because of this parsing the JSON string of that JSON Object just doesn't work.
Does anyone know of a workaround to explicitly set the property name in quotes?
I would love to just follow best practices and not use a dot in the property name but this is required for some requests in Looker. I was working for a client in Looker so I needed a workaround.
Strictly speaking of JSON format, ALL field names must be in quotes. This is required for interoperability, like sending data to a REST API, etc. Within these quotes, virtually any string is allowed per the JSON spec.
In JavaScript, this is looser, JavaScript objects don't need quotes around property names when these names are simple (a-z, A-Z, 0-9, _, $), otherwise, quotes are needed to disambiguate for language parsing reasons.
IF you want a property to be set from a string value, just do this:
{
[myStringVariable] : true
}
Without the need to fumble with quotes, this allows you to set a property with virtually any string. So you can set some constants in your code defining these field names, and then just do this in a consistent manner:
const FIELD1 = "my& crazy**field-name"; // Or from some schema definition.
// etc. other field consts.
let myObject = {
[FIELD1] : true
// .. etc.
}
Note also, that within this [ ] notation, you can put any valid JavaScript expression that can evaluate to a string, such as [myFields.field1Name] and even things like [(someCondition ? "unknown" : "myField")]
Finally, none of this is any kind of "standard", just mechanisms you may want to consider for cases where your field names are not controlled by you -- because when they are controlled by you, you should keep them simple for clarity.

why we need to use [ ] for access variable name include hyphan?

Either if you saying '-' takes as a subtract expression.
eg. Json = {'Me-m':123}
But have you idea why we need to use [] for access this hyphen variable.
Such like that Json['Me-m'].
Writting
Json.Me-m
will evaluate to
Json.Me - m
It will try to access Me property from Json object and subtract m variable, which probably will be undefined.
Because Me-m is not a valid property name to be used as property hence you are forced to use as Maps read this or check here for a valid propert name
That's because '-' has a meaning in javaScript, so if you write Json.Me-m JavaScript interprets: 'Substract the value of the variable m to the value of the attribute Me of the object ``Json`'.
In javascript, you can access any member of an object by name, using [], and inside a string, javascript is not going to try to evaluate anything, so when you write Json[Me-m], it's interpreted as: 'Retrieve the value of the member named Me-m of the object Json'
The reason is simple: in Javascript each object it's an indexed key/value dictionary, accessing to the variable with the "." it's a shortcut, and obviously the fact of the "dictionary object" it's a performance issue, but despite of this matter, javascript it's really fast in comparison with other scripting language.
Answering your question, by desing an index can be a string containing the "-" char, but not a property... so if you have a property with that char, it won't be accessible with the "." notation.
Because you are passing a special character in key part of obj and for accessing that value of obj we need to use [].
eg. json['Me-m']

Javascript Objects and keys

The following command shows the properties of an Object.
var keys = Object.keys(result);
Output: [requester.client.id,request.id]
When I try to print an alert(result[request.id]) or alert(result.request.id) I dont get the values. Is there something I am missing?
In JavaScript objects keys are strings, though they can have periods. What you probably getting as the output is ['requester.client.id','request.id'], so it should be accessed as result['requester.client.id'].
Your result object has properties named "requester.client.id" and "request.id".
You need to do alert(result["request.id"]).
result[request.id] does not work because request here is treated as a variable name, and you probably have no variable named request.
result.request.id is closer, but it also fails because the property name has a period in it, so the parser treats this as the the id property of the request property of result.

Javascript: Using a string to acces objects property

If I have a string like
var s = someString;
But I do NOT know the value of that string, since the program obtains it from external file, and I wanted to use that string to access an objects property, like:
alert(obj.s)
//or
alert(obj[s]);
How would I do that? The code I wrote doesn't work, the alerts are just empty (and I'm positive that s is NOT empty AND that there is a property with the same value as s). But when I try to access an object normally it works fine (using a property name I already know):
alert(obj.name);
//or
alert(obj["name"]);
So...any ideas? Thanks

Javascript Object Access

I am using a Comet Push Engine called APE (Ajax Push Engine) and whenever I receive a realtime event I receive it in an javascript object called 'raw'.
So if for example if the raw object contains a 'location' value, I can print 'raw.location' and it will give me the value,
alert(raw.location);
So I have another object called currentSensor, which contains a value like this (in my example it would contain the string 'location'):
currentSensor.value
How do I programmatically use the currentSensor.value variable to access the 'raw' object? I have tried this:
var subsensor = currentSensor.sensorKey;
and then
alert(raw.subsensor);
But I keep getting undefined because the raw object doesn't contain a key called "subsensor" its actually "location". I hope this makes sense!
Thanks!
When using dot-notation, you use a literal property name. If you want to use a string, use square bracket notation.
foo.bar === foo['bar'];
Strings can be variables.
baz = 'bar';
foo.bar === foo[baz];
like this:
console.log(raw[currentSensor.value]);
Here you go:
alert(raw[subsensor]);
The dot syntax cannot help you when you need to access variable indexes. You need to use the array access method.
Note: The dot access method is just syntactic sugar and is not really needed in any place, but it is useful for code readability.
For your entertainment:
"1,2,3"["split"](",")["join"]("|")

Categories