Getting object properties that start with a number [duplicate] - javascript

This question already has answers here:
Can I get a javascript object property name that starts with a number?
(2 answers)
Closed 8 years ago.
I've got an object where one of the properties starts with a number. I've read that this was allowed, but I'm getting this error:
SyntaxError: identifier starts immediately after numeric literal
var stats = {"LOAD_AVG":{"1_MIN":0.08,"5_MIN":0.08,"15_MIN":0.08},"COUNTS":{"TOTAL":888,"RUNNING":1,"SLEEPING":887,"STOPPED":0,"ZOMBIE":0},"CPU":{"USER_CPU_TIME":8.9,"SYSTEM_CPU_TIME":2.4,"NICE_CPU_TIME":0,"IO_WAIT_TIME":1,"HARD_TIME":0,"SOFT_TIME":0.1,"STEAL_TIME":0},"MEMORY":{"PHYSICAL":{"TOTAL":"3921.98mb","IN_USE":"3682.652mb (93.9%)","AVAILABLE":"239.328mb (6.1%)","BUFFERS":"266.492mb (6.8%)"},"SWAP":{"TOTAL":"4194.296mb","IN_USE":"64.264mb (1.5%)","AVAILABLE":"4130.032mb (98.5%)","CACHE":"1191.328mb (28.4%)"}}};
//works fine
window.alert(stats.COUNTS.TOTAL);
//doesn't work
window.alert(stats.LOAD_AVG.1_MIN);
Here's a fiddle.
How can I access the properties that begin with a number without rewriting the PHP that generated it?

You can use bracket access for properties that aren't valid JavaScript identifiers, that goes for property names with spaces or other language symbols like +, *
window.alert(stats.LOAD_AVG["1_MIN"]);
You can use bracket access anywhere really
window.alert(stats["COUNTS"]["TOTAL"]);

Related

How do I get values from an object using dot notation [duplicate]

This question already has answers here:
JavaScript object: access variable property by name as string [duplicate]
(3 answers)
Closed last year.
How do I get values from an object using dot notation when I have a variable that changes.
console.log(`${getData}.BUTTON_${item.UUID}`);
// outputs: [object Object].BUTTON_1
In the object is a value for BUTTON_1. My item.UUID is a number that will change to a different button number. I need to be able to get the value for the button number
what works
console.log(getData.BUTTON_0);
My button number will be between 0 and 4 example getData.BUTTON_0, getData.BUTTON_1 ...
currently I need the button number to be a variable however the following does not work
console.log(`${getData}.BUTTON_${item.UUID}`);
JavaScript object: access variable property by name as string
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors#bracket_notation
console.log(getData[`BUTTON_${item.UUID}`]);

the way of accessing the number element of object in javascript in '.' causes an error [duplicate]

This question already has answers here:
Object property name as number
(6 answers)
How can I access object properties containing special characters?
(2 answers)
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 1 year ago.
First, I am a beginner of javascript.
Please understand asking this simple question.. (looks simple)
I was making a membership related webpage and encountered an error..
I was learned that to access the element of an object, I can use '.'(dot)
so I coded like,
It was a bit long object(json type contents) but.. to sum up,
dict1 = {'a':1, 'b':2, 'c':3};
dict2 = {1:'a', 2:'b', 3:'c'}
dict1.a
result: 1
dict2.1
result: Uncaught SyntaxError: Unexpected number
so the point is,
Someone may think, "if you can see the elements, why would you access the element by '.'(dot). if you already know it can cause the error."
but the data is user input and users can input any data as they wish.
Javascript provides '.'(dot) operator for Object but not working for number Element??
or do I use the dot in wrong way?
If you use dot notation, your key must be a valid identifier (start with a letter, $ or _). So in this case you would need to use dict2['1'].
You can do something like this to get the values
// With the braces you can get the values even if the key is a number
let dict2 = {
1: 'a',
2: 'b',
3: 'c'
}
console.log(dict2[1])
// Even if you want to access the values that are having keys like strings you can use the same operator
dict1 = {'a':1, 'b':2, 'c':3};
console.log(dict1['a'])

Targeting an array of objects in JavaScript [duplicate]

This question already has answers here:
Unable to access JSON property with "-" dash [duplicate]
(5 answers)
How can I access object properties containing special characters?
(2 answers)
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 5 years ago.
I have a value in this format:
var state = [{"industry-type":"football","your-role":"coach"}]
I would like to output "football". How can I do this?
I've tried state[0].industry-type but it returns an error:
Uncaught ReferenceError: type is not defined
Any help appreciated.
It does not like the '-' in your property name, try:
state[0]['industry-type']
This happens because you can't access a property with - directly.
var state = [{"industry-type":"football","your-role":"coach"}];
console.log(state[0]['industry-type']);
The - symbol is reserved in Javascript, you cannot use it to refer to an object's property because Javascript thinks you're trying to do subtraction: state[0].industry - type; Hence the error "Uncaught ReferenceError: type is not defined" - it is looking for a variable named type to subtract with, which it can't find.
Instead, refer to it by:
state[0]['industry-type']
Because in Javascript, object.property and object['property'] are equal.
For what it's worth, if you have control over those names, it is best practice in Javascript to name things with Camel Case, so your variable would be defined as:
var state = [{"industryType":"football","yourRole":"coach"}]
Then, you could access it like:
state[0].industryType
In order to be able to use dot notation then your:
...property must be a valid JavaScript identifier, i.e. a sequence of
alphanumerical characters, also including the underscore ("_") and
dollar sign ("$"), that cannot start with a number.
From MDN
Like the other answers pointed out, you have to use square bracket notation to access property names of an object that are not valid JavaScript identifiers.
e.g.
state[0]["industry-type"]
Related SO question:
What characters are valid for JavaScript variable names?
You'll need to use bracket notation for the attribute -
state[0]['industry-type']

How do I correctly include a dash in an object key in javascript? [duplicate]

This question already has answers here:
How can I access object properties containing special characters?
(2 answers)
Closed 1 year ago.
When I try to use a code like this:
jQuery.post("http://mywebsite.com/", {
array-key: "hello"
});
I get this error:
Uncaught SyntaxError: Unexpected token -
I tried surrounding the key in quotation marks, but nothing happened. I'd like to know if it's because of some other mistake I am making at the other website or because that's not how to include a dash in an object's key. And if it's not I'd like to know how to do it. Thanks in advance.
jQuery.post("http://mywebsite.com/", {"array-key": "hello"});
should be correct. If this doesn't work, the issue is not with your request.

Usage of toString in JavaScript [duplicate]

This question already has answers here:
Calling member function of number literal
(3 answers)
Closed 9 years ago.
I'm reading through Douglas Crockford's JavaScript: The Good Parts, and I'm at the point where he defines a fade function. Part of this code boils down to this:
var level = 1;
var hex = level.toString(16);
So I run this in my browser's console to see what I get....
var level = 1;
level.toString(16);
Hey, it returns "1"... Fabuloso! Wunderbar!
Then to be cheeky, I try this to see what I get...
1.toString(16);
And I get
SyntaxError: Unexpected token ILLEGAL
What the what? If level is a variable equal to 1, and running this method on level works fine, then why doesn't running this method on the actual number 1 work? I tried a similar experiment with the toPrecision() method and that worked fine in both cases. What's the issue here? Is this another one of those inherent flaws in the JavaScript implementation, or am I missing something? I am testing in Google Chrome.
Related: Stack Overflow question Why don't number literals have access to Number methods?.
It's just a language grammar limitation.
Since 1. is a legal literal number (and 1.t is not) the tokeniser will split this into the following tokens:
1.
toString
(
)
And that's an illegal sequence of tokens. It's object method, instead of object . method.
In the working versions in #Joey's answer, the braces prevent the tokenizer from treating the dot as part of the number literal instead of as a separate token, as does writing:
1.0.toString()
or
1..toString()
since the tokenizer knows that the second dot must be a token on its own, and not part of the number literal.
You need 1..toString or (1).toString to get the number literal
level is a variable (and thus an object).
1 is a literal. They are not objects and the interpreter thinks about them completely differently.
http://www.cs.brown.edu/courses/bridge/1998/res/javascript/javascript-tutorial.html#4

Categories

Resources