Cannot read properties of a JavsScript function [duplicate] - javascript

This question already has answers here:
Javascript Object - Key beginning with number, allowed?
(4 answers)
Closed 6 years ago.
I have a php array that I'm json_encodeing into a JavaScript object. When I preview the object in console, it looks something like this:
Object { 1="some text", 2="something else", 3="extra text"}
Shouldn't I be able to read the value for index 1 like this (pretending my object name is obj)?
obj.1
Doing that gives me the undefined error message. How would I access the value for the exact index of 1?

You can only access a property using dot notation if the property name is a valid identifier. Identifiers cannot start with a number.
You have to use square bracket notation for other properties.
obj[1]

1- Do not use the word Object
2- Use colon instead of equal
3- Do not forget the semi-colon
4- if your key is number, use braces.
var obj = { 1:"some text", 2:"something else", 3:"extra text"};
console.log(obj[1]);

Related

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

Why I can't access JSON dictionary element using dot notation? [duplicate]

This question already has answers here:
Object property name as number
(6 answers)
Closed 6 years ago.
I have a following JSON representation:
var collectionCopy = JSON.parse(JSON.stringify(
{
1 : {
2: "2"
}
}
));
Why cant I access key "2" using dot notation (i.e. collectionCopy.1.2) ?
You can use the dot notation for accessing an object's properties only on a valid identifiers in the language.
And since numbers (or anything that starts with a number) are not a valid identifiers you can access it (as a property of an object) only with the bracket notation.
This is because the keys are strings not actual numbers:
to access it use:
collectionCopy[1][2]
or
collectionCopy['1']['2']
Relevant docs on accessing properties

how to use . point into javascript variable name [duplicate]

This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 7 years ago.
I have and API that return an Array of object like the following:
{
"form_submit.form_submit_id": 7987,
"form_submit.exported": false,
"form_submit.updatedAt": "2016-01-18T16:13:16.813Z",
"form_submit.user.user_id": 14,
"form_submit.user.name": "Hugo Bismarck",
},
If I use the . on my javascript for example to get the first element
var test = array[0].form_submit.form_submit_id;
get the following error
array[0].form_submit.form_submit_id is undefined
the problem is that the name of the attributes have points, so how can acces to this attributes?
You can use in this case the bracket notation:
property_name is a string. The string does not have to be a valid identifier; it can have any value, e.g. "1foo", "!bar!", or even " " (a space).
var test = array[0]['form_submit.form_submit_id'];

Getting object properties that start with a number [duplicate]

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

Categories

Resources