Table of contents
- Objects
- Accessing non-existent JavaScript properties
- JavaScript Objects are Mutable
- JavaScript for...in loop
- Properties and values of a JavaScript object
- Delete operator
- JavaScript Object Methods
- shorthand property name syntax for object creation
- this Keyword
- 1. Update a Property of an Object#
- 2. Turn an Object's Keys into an Array#
- 3. Turn an Object's Values into an Array#
- 4. Turn Array or Map sets into an Object#
- 5. Shallow Clone an Object#
- 6. Deep Clone an Object with only variables#
- 7. Merge two objects into the original variable#
- 8. Merge two objects into a new variable#
- 9. Prevent new items being added to an object, but allow previous items to be changed#
- 10. Prevent any changes to an object#
- 11. Turn Object into a String#
- 12. Turn String into an Object#
- 13. Check if Object has a property#
- 14. Make a Property of an Object Unwritable so you can't change it#
- 15. Ignore certain properties when using a for loop#
- 16. Convert Object to Array sets#
Objects
An object is a built-in data type for storing key-value pairs. Data inside objects are unordered, and the values can be of any type.
Accessing non-existent JavaScript properties
When trying to access a JavaScript object property that has not been defined yet, the value of undefined
will be returned by default.
JavaScript Objects are Mutable
JavaScript objects are mutable, meaning their contents can be changed, even when they are declared as const
. New properties can be added, and existing property values can be changed or deleted.
It is the reference to the object, bound to the variable, that cannot be changed.
JavaScript for...in
loop
The JavaScript for...in
loop can be used to iterate over the keys of an object. In each iteration, one of the properties from the object is assigned to the variable of that loop.
Properties and values of a JavaScript object
A JavaScript object literal is enclosed with curly braces {}
. Values are mapped to keys in the object with a colon (:
), and the key-value pairs are separated by commas. All the keys are unique, but values are not.
Key-value pairs of an object are also referred to as properties.
Delete operator
Once an object is created in JavaScript, it is possible to remove properties from the object using the delete
operator. The delete
keyword deletes both the value of the property and the property itself from the object. The delete
operator only works on properties, not on variables or functions.
JavaScript Object Methods
JavaScript objects may have property values that are functions. These are referred to as object methods.
Methods may be defined using anonymous arrow function expressions, or with shorthand method syntax.
Object methods are invoked with the syntax: objectName.methodName(arguments)
shorthand property name syntax for object creation
The shorthand property name syntax in JavaScript allows creating objects without explicitly specifying the property names (ie. explicitly declaring the value after the key). In this process, an object is created where the property names of that object match variables which already exist in that context. Shorthand property names populate an object with a key matching the identifier and a value matching the identifier’s value.
this
Keyword
The reserved keyword this
refers to a method’s calling object, and it can be used to access properties belonging to that object.
Here, using the this
keyword inside the object function to refer to the cat
object and access its name
property
With arrays, there are usually a set number of specific things you want to achieve. Below is a list of pretty much any action you would want to perform on objects, and how to do it in Javascript. If you have any more, please tell me via twitter and I will add them (along with a link to your social media of choice)
1. Update a Property of an Object#
Use the =
operator:
let object = {
'myName' : {
'FirstName' : 'Name',
'SecondName' : 'Surname'
},
'myAge' : 1043
}
// Updates myAge to 2043
object.myAge = 2043
2. Turn an Object's Keys into an Array#
Use keys()
:
let object = {
'myName' : 'Name',
'myAge' : 1043
}
// Returns [ 'myName', 'myAge' ];
let keys = Object.keys(object);
3. Turn an Object's Values into an Array#
Use values()
:
let object = {
'myName' : 'Name',
'myAge' : 1043
}
// Returns [ 'Name', 1043 ];
let values = Object.values(object);
4. Turn Array or Map sets into an Object#
Use fromEntries
:
let arrSets = [ ['myName', 'Name'], ['myAge', 1043] ]
/* Returns {
'myName' : 'Name',
'myAge' : 1043
} */
let generateObject = Object.fromEntries(arrSets);
5. Shallow Clone an Object#
Use assign()
or ...
:
let object = {
'myName' : 'Name',
'myAge' : 1043
}
// Creates a copy of object, which we can edit separately
let newObject = Object.assign({}, object);
// Creates a copy of object, which we can edit separately
let anotherClone = { ...object };
6. Deep Clone an Object with only variables#
Use JSON.parse(JSON.stringify())
:
let object = {
'myName' : {
'FirstName' : 'Name',
'SecondName' : 'Surname'
},
'myAge' : 1043
}
// Creates a copy of object, which we can edit separately
let newObject = JSON.parse(JSON.stringify(object));
newObject.myName.FirstName = 'Hello';
console.log(newObject, object);
/*
Returns {
myAge: 1043,
myName: {
FirstName: "Hello",
SecondName: "Surname"
}
}, {
myAge: 1043,
myName: {
FirstName: "Name",
SecondName: "Surname"
}
} */
7. Merge two objects into the original variable#
Use assign()
:
let object = { 'myName' : 'Name' }
let objectTwo = { 'myAge' : 1043 }
Object.assign(object, objectTwo);
console.log(object, objectTwo);
/* Returns {
myAge: 1043,
myName: "Name"
}, {
myAge: 1043
} */
8. Merge two objects into a new variable#
Use ...
.
let object = { 'myName' : 'Name' }
let objectTwo = { 'myAge' : 1043 }
let newObject = { ...object, ...objectTwo }
console.log(object, newObject);
/* Returns {
myName: "Name"
}, {
myName: "Name",
myAge: 1043
} */
Note: if you merge two objects with ...
, and there are duplicate keys (i.e. both have myAge), the second Object will overwrite the first.
9. Prevent new items being added to an object, but allow previous items to be changed#
Use preventExtensions()
:
let object = {
'myName' : {
'FirstName' : 'Name',
'SecondName' : 'Surname'
},
'myAge' : 1043
}
Object.preventExtensions(object);
// Throws a TypeError
object.myLocation = '123 Fake Street';
10. Prevent any changes to an object#
Use freeze()
:
let object = {
'myName' : {
'FirstName' : 'Name',
'SecondName' : 'Surname'
},
'myAge' : 1043
}
Object.freeze(object);
// Throws a TypeError
object.myLocation = '123 Fake Street';
// Throws a TypeError
object.myAge = 2043
11. Turn Object into a String#
Use JSON.stringify()
:
let object = {
'myName' : {
'FirstName' : 'Name',
'SecondName' : 'Surname'
},
'myAge' : 1043
}
// Returns {"myName":{"FirstName":"Name","SecondName":"Surname"},"myAge":1043}
console.log(JSON.stringify(object))
12. Turn String into an Object#
Use JSON.parse()
:
let stringObject = '{"myName":{"FirstName":"Name","SecondName":"Surname"},"myAge":1043}';
/* Returns {
'myName' : {
'FirstName' : 'Name',
'SecondName' : 'Surname'
},
'myAge' : 1043
} */
console.log(JSON.parse(object))
13. Check if Object has a property#
Use hasOwnProperty()
:
let object = {
'myName' : {
'FirstName' : 'Name',
'SecondName' : 'Surname'
},
'myAge' : 1043
}
// Returns true
console.log(object.hasOwnProperty('myName'))
14. Make a Property of an Object Unwritable so you can't change it#
Use defineProperty()
and change writable
:
let object = {
'myName' : {
'FirstName' : 'Name',
'SecondName' : 'Surname'
},
'myAge' : 1043
}
Object.defineProperty(object, 'myAge', {
writable: false,
});
// object.myAge remains 1043
object.myAge = 2043;
15. Ignore certain properties when using a for loop#
Use defineProperty()
and change enumerable
. If we set enumerable to false, that item will be ignored in forEach
loops.
let object = {
'myName' : {
'FirstName' : 'Name',
'SecondName' : 'Surname'
},
'myAge' : 1043
}
Object.defineProperty(object, 'myAge', {
enumerable: false,
});
// Returns only 'myAge'
Object.keys(object).forEach(function(item) {
console.log(item);
});
16. Convert Object to Array sets#
Use entries()
:
let object = {
'myName' : 'Name',
'myAge' : 1043
}
// Returns [ [ 'myName', 'Name' ], [ 'myAge', 1043 ]];
let entries = Object.entries(object);
S.No | Methods | Description |
1 | Object.assign() | This method is used to copy enumerable and own properties from a source object to a target object |
2 | Object.create() | This method is used to create a new object with the specified prototype object and properties. |
3 | Object.defineProperty() | This method is used to describe some behavioral attributes of the property. |
4 | Object.defineProperties() | This method is used to create or configure multiple object properties. |
5 | Object.entries() | This method returns an array with arrays of the key, value pairs. |
6 | Object.freeze() | This method prevents existing properties from being removed. |
7 | Object.getOwnPropertyDescriptor() | This method returns a property descriptor for the specified property of the specified object. |
8 | Object.getOwnPropertyDescriptors() | This method returns all own property descriptors of a given object. |
9 | Object.getOwnPropertyNames() | This method returns an array of all properties (enumerable or not) found. |
10 | Object.getOwnPropertySymbols() | This method returns an array of all own symbol key properties. |
11 | Object.getPrototypeOf() | This method returns the prototype of the specified object. |
12 | Object.is() | This method determines whether two values are the same value. |
13 | Object.isExtensible() | This method determines if an object is extensible |
14 | Object.isFrozen() | This method determines if an object was frozen. |
15 | Object.isSealed() | This method determines if an object is sealed. |
16 | Object.keys() | This method returns an array of a given object's own property names. |
17 | Object.preventExtensions() | This method is used to prevent any extensions of an object. |
18 | Object.seal() | This method prevents new properties from being added and marks all existing properties as non-configurable. |
19 | Object.setPrototypeOf() | This method sets the prototype of a specified object to another object. |
20 | Object.values() | This method returns an |
A JavaScript object is a collection of named values. The named values, in JavaScript objects, are called properties. Objects are Variables Containing Variables JavaScript variables can contain single values. Objects are variables too. But objects can contain many values. The values are written as name : value pairs (name and value separated by a colon). Accessing Object Properties You can access object properties in two ways: objectName.propertyName or objectName["propertyName"]
how to change property name value.?
how to add property name with value manually
how to delete property name in any object?