# Manipulating Objects
# Square Brackets vs Dot Notation
The first way we access any property or method in an object is with dot notation. That means putting a period between each object name and property name.
let obj = {
name: 'Bubba',
age: 44,
};
obj.name; // has the value 'Bubba'
obj.age; // has the value 44
2
3
4
5
6
There is an alternative syntax that uses square brackets.
let obj = {
name: 'Bubba',
age: 44,
};
obj['name']; // has the value 'Bubba'
obj['age']; // has the value 44
2
3
4
5
6
Note the quotation marks around the property names. All Object property names (for our purposes) will be Strings.
So, why the two approaches? - With the square brackets we can put a variable inside the brackets instead of a string.
let obj = {
name: 'Bubba',
age: 44,
};
let n = 'name';
let a = 'age';
obj[n]; // has the value 'Bubba'
obj[a]; // has the value 44
obj.n; // this would fail because JS would look for obj.n or obj['n']
obj.a; // this would fail because JS would look for obj.a or obj['a']
2
3
4
5
6
7
8
9
10
11
So, if you are trying to dynamically update an object or access it's properties inside a function and you need the function to work with any object or any property then you need to use variables that contain those references. With the square brackets we can reference any property.
function doUpdate(someObj, someProp, someVal) {
//this function can update the value of any property inside any object
someObj[someProp] = someVal;
}
2
3
4
# Checking for Property Existence
As a best practice, when you are going to change an object by updating the value of a property, deleting a property, or adding a new property, then you should check to see if that property already exists.
There are two ways that we can check for the existence of a property on any object. We can use the in
operator or the hasOwnProperty()
method. The in
operator is the simplest and shortest to write.
let obj = {
depth: 8,
width: 34,
ref: 'AB393620',
};
if ('depth' in obj) {
//there IS a depth property in the Object `obj`
}
if (obj.hasOwnProperty('width')) {
//there IS a width property in the Object `obj`
}
2
3
4
5
6
7
8
9
10
11
# Deleting Properties from Objects
When you are done with a property and want to get rid of it there are two things we can do. First, to permanently delete the property, we use the delete
keyword.
delete obj['ref']; //removes the property `ref` from the Object `obj`.
Now, if you only want to temporarily remove the value, but still keep the property to use later with a new value, we can just update its value to null
.
obj.myprop = null;
obj['otherProp'] = null;
//both these properties still exist but their value is now null.
2
3