Targeting an array of objects in JavaScript [duplicate] - javascript

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

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

Cannot read properties of a JavsScript function [duplicate]

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

Referencing object's property name with hyphen [duplicate]

This question already has answers here:
JavaScript object: access variable property by name as string [duplicate]
(3 answers)
Closed 6 years ago.
I have defined an object with properties that have hyphen in their names.
var data = {
"foo-bar": "value",
"this-that": "another value"
}
Now I need to reference this property in JS, but both these ways result in syntax error.
console.log( data.foo-bar )
and
console.log( data."foo-bar" )
So my question is. How can I access a property that contains hyphen in the name in JS?
Disclaimer: The server-side functionality require hyphen-naming of the properties and I don't really feel like rewriting somebody else's whole script that takes the input params like this. And yes, I know this current way is not the most clean approach possible.
You Could use data["foo-bar"] Instead.

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

what is a difference myObj.a=b vs myObj[a]=b [duplicate]

This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 8 years ago.
I was reading here on stack overflow that these are not equal. So what is the difference.
What happened is that in 2nd case value was assigned as the property of myObj. So if b='abc';
then myObj.abc was now available.
I had always thought same thing but [] version was used when name were weird ones.
Dot notation takes an identifier that is the property name. The square bracket notation accepts a string representation of the property name.
Given var a = "a"; then myObj.a = b and myObj[a] = b and myObj["a"] = b are equivalent.
The difference between myObj.a=b and myObj[a]=b is that in the first case you are accessing an attribute called a in the object. In the second you are accessing an attribute whose name is in a variable called a.
On the other hand, myObj.a=b and myObj["a"]=b would be equivalent.
a lot, results would depends on a var value. but ["a"] would be the same as .a

Categories

Resources