Accessing Properties in object [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript property access: dot notation vs. brackets?
<script>
var foo = {
name: 'kevin'
};
document.write(foo.name);
document.write(foo['name']);
var cool = 'name';
document.write(foo.cool);
document.write(foo[cool]);
</script>
Why does foo.cool returns me undefined where as foo[cool] returns
me kevin.
How does cool actually refer to my name property in foo object.

A cool property is not defined on foo, so foo.cool is undefined. If you did foo.name, it would return kevin.
cool in foo[cool] is the one you defined in the line above it, so it is actually foo['name'], which is defined and has the value kevin.

You can access the properties either...
Literally by their name: property.name
Indirectly by an expression that evaluates to their name: property[expr].
Hence if the expression cool has value 'name', then foo[cool] is the same as foo['name'] or foo.name.
The brackets also allow for...
1) more complex expressions like foo["data_"+variable] to easily access fields named like data_something,
2) property names that aren't simple identifiers, for example you could say foo["I'm long!"].
I hope this explanation brightens things up for you.

In var foo = { name: 'kevin'}; You store an object or a dictionary to that variable... which is now a key-value pair... so you can access the value of an object using the key...
since its a key value pair... you can't access it using '.' operator... because foo is not a class... type of foo will be a dictionary or object...
so, to access the value you need to use the [] paranthesis...

Related

JS - Difference between period and [] while accessing a JSON object [duplicate]

This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 4 years ago.
What is the difference between accessing a JSON object using period (.) and [] notation in Javascript. For instance,
var person = {
"firstName": "Foo",
"lastName":"Bar"
}
I'm sure accessing the "firstName" and the "lastName" variables give me the same output type (string),i.e.
console.log(typeof person.firstName); // returns string
console.log(typeof person.lastName); // returns string
Also, accessing it both the ways, using . or [] will give me the same result:
console.log(person.firstName); // returns Foo
console.log(person['firstName']); // returns Foo
I'm trying to understand when to use which notation and when not to and the actual difference between them. I read somewhere that we can't use the dot notation if the data is complicated, I'm not sure what it means, tested out a couple of sample input data:
"firstName": " Foo Bar "
"firstName": "####$% Foo Bar!!!"
Interestingly, both gives me the same result, can someone please explain me what's the actual difference between these two notations and when to access which?
They are both valid ways of accessing Object Values.
Welcome to Stackoverflow!
The main difference between the two is that using bracket notation allows you to define and access properties with spaces in them -- something one cannot do with dot notation.
var foo = {
"I AM BAR": 1
}
If you wanted to access the single property "I AM BAR" on foo, with bracket notation, it would look like: foo["I AM BAR"]. This is not possible with dot notation.
There are not difference.
The [] approach is useful when you need find a key with a variable.
Like:
const theKey = 'test';
theArray[theKey]; // this work
theArray.theKey; // this dont work
Using dot notation you must provide the exact propertyName but you are able to work with the name when using [].
var person = {
"firstName": "Foo",
"lastName":"Bar"
}
Using . you can only access by
console.log(person.firstName); // returns Foo
Using [] you could access value with variable
let couldChange = 'Name';
console.log(person['first'+couldChange]); // returns foo
console.log(person['last'+couldChange]); // returns bar
Most of the time you will use dot notation. Unless you need the property on the object you need to access to be dynamic. This is because the value you pass into the brackets could be a variable as long it resolves to a string. Check out this link for more info:
https://codeburst.io/javascript-quickie-dot-notation-vs-bracket-notation-333641c0f781
Most of the time, there's no difference, see Property accessors (MDN), but you cannot use dot notation when the property name is not a valid identifier name, e.g. when it's representation is not a string, or when you need to use a variable to name the property.
obj[1] // is valid
obj["1"] // is the same
obj.1 // is NOT valid
const propertyName = 1;
obj[propertyName] // the same as obj[1]
obj.propertyName // not same
Using brackets can allow you to use a variable value to access object properties whereas dot notation won't. For example:
var propName = 'age';
var o = {
name: 'Tom',
age: '29',
about: 'He\'s a cool guy!'
};
console.log(o.propName); // <-- Will be undefined
console.log(o[propName]); // <-- Bingo

Why symbol-type key in Object have a bracket around them [duplicate]

This question already has answers here:
What do square brackets around a property name in an object literal mean?
(2 answers)
Closed 5 years ago.
I just started JS, wondering why there are [] around Symbol. For example: in an object.
var bow = {
[Symbol('apple')] : something,
[Symbol('banana')] : something,
....
}
Also, when it comes to iterator:
var iterableObject = {
[Symbol.iterator] : function() {.....}
}
Can anyone explain what is the use of these [] around them? I googled a while but didn't find satisfied answer, thank you in advance.
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors
The bracket notation is just another way of accessing a property on an object. In particular, it's used when the property name is not valid for use with the dot notation, such as Symbol.iterator.
You may also want to look at computed property names: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names
These are similar but are instead used to set properties when an object is defined rather than get properties from an already defined object.
The square brakets are just part of object literal syntax.
When you make an object using object literal syntax it is now possible to use variables to set the keys inside the object.
const string = 'whatever'
const normalObject = {
[string]: 'something else'
}
This results in normalObject having one property, 'whatever' pointing to 'something else'
// normalObject
{ whatever: 'something else' }
The use of brackets in object literal syntax is just to allow you to use a variable to set the key in an object.
bringing this back to your example this is just allowing you to use Symbols as keys in your object.
You may have noticed that this is a little weird. Up until very recently an object could only have String keys. Symbols are not the other thing you can use as keys in an object.
var bow = {
[Symbol('banana')] : something,
[Symbol('banana')] : something,
....
}
this will result in an object with two different Symbol(banana) pointing to something.

Why is this json example an object is parsed as an array [duplicate]

This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 8 years ago.
I have this JSON code :
{
"query": {
"pages": {
"-1": {
"ns": 0,
"title": "StackOverflow",
}
}
}
}
I parsed it into a JSON object :
data = JSON.parse(jsonString);
Why to access the object -1 I must do data.query.pages[-1] not data.query.pages.-1. In this example pages is not an array but an object.
It's not an array, it's an object. Both object["name"] and object.name are identical ways of accessing a property called name on the given object.
You cannot access an object property with object.-1, simply because that's a syntax error, the same way you can't use object.+1 or object.[1 or object./1. They're all valid names for a property of an object, but they're syntactically invalid when using object.propertyName syntax.
The other caveat is that you cannot have property names which are integers. Setting or getting object[-1] is identical to object["-1"] as the property name is converted to a string. It would be identical to accessing object.-1 if that were valid syntax.
You can't do data.query.pages.-1 for the same reason you can't do var -1;: -1 is not a valid identifier.
But that's not a problem.
foo.bar // Access member bar of object foo
is just a shortcut for
foo["bar"] // Access member bar of object foo
so you can do
data.query.pages["-1"]
You could even do
data["query"]["pages"]["-1"]
Bracket notation has nothing to with arrays, it's just another way to access properties. In fact, the reason why we can only use bracket notation for arrays is because of the evaluation rules: To use dot notation, the property name must be a valid identifier name.
Or simply put:
You can only use dot notation if the property name would be a valid variable name or a reserved word.
And -1 doesn't fall in that category (you can't do var -1 = 'foo'; for example).
Examples for invalid identifier names:
0foo, -foo, &bar
anything that doesn't start with a letter, _ or $
foo-bar, foo+bar, foo bar
anything that contains something that is not a letter, a digit, _ or $ (or fall into specific unicode ranges, see the spec).
However, using reserved words is possible, even though they can't be used as variables:
foo.if // valid
var if = 42; // invalid

Is there a way to "get" javascript objects using a function in the same way getElementById() is able to get html element objects?

document.getElementById('coolid').innerHTML = "pretty cool";
The code above will, to my knowledge, access an html element object by id named 'coodid" and that object, being an element object, has a property of "innerHTML" which allows me to replace that HTML nodes text with the text "pretty cool".
I also know getElementsByName() and getElementsByClass(), etc...these all allow me to access DOM elements (which to my knowledge are objects). Ok, that's great. But is there some way to access objects I create as well? Like this:
var person = {
name : "John",
}
object.reallyCoolImaginaryGetMyObjectFunction('person').name = "Tom";
I know this might seem quite strange and perhaps even pointless, but just out of curiosity I've been wondering about this. Does anyone have any idea? Thanks.
You can if they're stored on an object, and there's one special case (globals) which are automatically stored on window.
You do it using bracketed notation and a string, e.g.:
var obj = {
foo: "bar"
};
console.log(obj["foo"]); // "bar"
Or of course if it's a global variable:
console.log(window["foo"]); // "bar"
...since global variables are properties of the global object, and we can refer to the global object on browsers as window.
Details: JavaScript has two ways to access properties: Dot notation with literal names (obj.foo), and bracketed notation with strings (obj["foo"]). In the latter case, the string can be the result of any expression, e.g.:
// These all do the same thing, in the end
console.log(obj["foo"]);
console.log(obj["f" + "o" + "o"]);
var x = "foo";
console.log(obj[x]); // x contains the string

Access the content of a variable who's name is in another variable [duplicate]

This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 8 years ago.
I have two variables, one holds extra info about an object, and is named extra_info + the id of the object. The other holds the name to that variable:
selector = 'extra_info' + subscid;
I am trying to access the data stored in the variable that holds the extra info, but I can't seem to access it. Stupid, I know :-)
EDIT: So, the name of the variable that I in the end need to access is:
extra_infoXXXXX
where XXXXX is stored in subscid.
No quotes:
selector = extra_info + subscid;
Or, and I'm loathe to suggest this because it's a red flag of bad design, you can use eval():
selector = eval('extra_info' + subscid);
(Obilgatory "eval is evil" link)
EDIT
It sounds like you should stored your extra_info in an array object, with the subscid for its indexes properties!
To access, do something like extra_info[subscid].
Edit:
From your comment:
extra_infoXXXXX holds a string
...it sounds like if subscid contains "foo", you want to get the value of extra_infofoo. If so, you'll need an object to look that up; otherwise, you'll be forced to use eval.
If these extra_infoxxxx variables are globals, you can look them up on window:
selector = window['extra_info' + subscid];
If not, I hate to say, you're stuck with eval:
selector = eval('extra_info' + subscid); // Blech
But note that if you're doing that, it's best to step back and reevaluate (no pun!) your design. For instance, perhaps you could make an object with the extra info as properties:
var extra_info = {
foo: "bar"
};
Then you could look up the information like this:
selector = extra_info[subscid];
Original Answer:
It's very hard to tell from the information you've given, but I think you're looking for:
selector = extra_info[subscid];
...assuming that subscid contains the name of the property on extra_info that you want to access.
In JavaScript, you can access a property on an object using dotted notation and a literal property name:
x = foo.bar;
...or using bracketed notation and a string property name:
x = foo["bar"];
In the second case, the string can be the result of any expression. So for instance:
b = "bar";
x = foo[b];
or even
x = foo['b' + 'a' + 'r'];
To get the variabale do like this,
selector = extra_info+""+subscid['XXX']

Categories

Resources