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

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

Related

Javascript Object Attribute With/Without quotes [duplicate]

This question already has answers here:
What is the difference between object keys with quotes and without quotes?
(5 answers)
Closed 4 years ago.
I am a JavaScript learner and want to know what is the difference between
var obj1 = {
attribute1 : 1
};
var obj2 = {
"attribute1" : 1
};
console.log(obj1.attribute1);
console.log(obj2.attribute1);
Both of them prints 1. Is there a major difference among them?
They are equivalent in your case.
Internally, they are the same.
What could change is the way you can access them with your code.
When using strings (quoted properties), you can actually use more exotic names for your properties :
var obj3 = {
"attribute with space": 1,
"123AttributeStartingWithANumber": 1,
}
In my example, you cannot access those attribute names via the obj1.attributeName syntax (but you can with the brackets notations : obj1["attribute with space"] or obj1["123AttributeStartingWithANumber"] .
This is because "attribute with space" or "123Attribute" are not valid identifiers in JS.
Note that in your example you can also use the bracket notation :
console.log(obj1["attribute1"]);
console.log(obj2["attribute1"]);
In summary, to quote deceze's comment :
Quoted properties and bracket notation always work, unquoted
properties and . dot access is shorthand for when your property name
is a valid identifier.
There is no difference.
Object literal syntax allows you to use a string or an identifier to provide the property name.
A string allows you to use characters (such as or .) which are not allowed in an identifier, but attribute1 has none of those characters in it.
You can make object keys with space in them if you declare them as strings:
var obj1 = {
attribute1 : 1 // but you cannot say my attribute1: 1 it will throw syntax error
};
var obj2 = {
"my attribute1" : 1
};
console.log(obj1.attribute1);
console.log(obj2.attribute1);

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.

How to add an empty array to object?

I'm having trouble adding my empty array into my object via the bracket notation method. I know how to get my empty array into the object via dot notation, but I just don't understand why the bracket notation isn't working for me.
Update: I understand my problem now; the context switch between dot notation & bracket notation blinded me & I completely failed to recall that in my 3rd block - animal[noises] (forgot the "") was trying to access the property value of the property noises, which I hadn't created yet in my object
Creating & adding properties to my object
var animal = {};
animal.username = "Peggy";
animal["tagline"] = "Hello";
Which will then create this:
animal {
tagline: "Hello",
username: "Peggy"
}
Why won't the following work when I'm trying to add it into my object?
var noises = [];
animal[noises];
I'm getting this in my console (same as above):
animal {
tagline: "Hello",
username: "Peggy"
}
I was able to get my result this way:
animal.noises = [];
Which outputs this into my console:
animal {
noises: [],
tagline: "Hello",
username: "Peggy"
}
But that still leaves me with the question: why doesn't this work via bracket notation?
Use
animal.noises = noises;
or
animal['noises'] = noises;
As when you are using animal[noises]; it means when you are trying to read data from the object.
For animal[noises],
animal is the object
and noises is the key/property of the object animal
And an array cannot be a key. If you want to put noises array in animal object you can do it as follows,
animal['noises'] = noises;
In your case you have to try
animal['noises']=noises
Array [] notation is used to get property of an object that requires a quote around it. Array notations are commonly used to get identifiers of objects having special characters included.say,
var animal={
"#tiger":'carnivore' // you can't have #tiger without quote as identifier
}
console.log(animal.#tiger) // it will give ERROR
console.log(animal['#tiger']) // it will print out 'carnivore'
this link has good explanation on array and dot notation .

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

Accessing Properties in object [duplicate]

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...

Categories

Resources