Object in Javascript: the full guide
In your daily work as a Javascript developer, you will use a lot of objects and you need some helpers on your toolbox to survive.
There are a lot of libraries that will do that for you (Lodash and Underscore are the most popular) but since ES6, itβs really easy to do without them.
You will also find some codebase with some ESlint rules to restrict this kind of libraries so itβs always good to know the native way.
π± Declare a new object
Here is the simple way to declare a new empty object:
// Using the object literal
const receipt = {};// Using the Object constructor
const receipt = new Object();
Of course, you can define some properties at the object creation:
// Using the object literal
const receipt = {
icon: 'πͺ',
name: 'Cookie',
};// Using the Object constructor
const receipt = new Object({
icon: 'πͺ',
name: 'Cookie',
});
You can use both, you will have the same result. On my side, Iβm using object literal declaration most of the time.
πΎ Duplicate an object
Sometimes, you need to duplicate an existing object. This will allow you to update an object without modifying the first one. Itβs a common practice in functional programming.
Like object creation, there are several ways to do this:
const receipt = {
icon: 'πͺ',
name: 'Cookie',
};// Using the spread operator
const clone = { ...receipt };// Using Object assign
const clone = Object.assign({}, receipt)
Most of the time, you will find the spread operator in modern codebases.
π Get a property in an object
Do you want to get a specific property in an object? Here is how:
const receipt = {
icon: 'πͺ',
name: 'Cookie',
};// Using the object destructuring (my favorite):
const { name } = receipt;// Destructuring a property with an alias:
const { name as receiptName } = receipt;// Using the dot notation
const name = receipt.name;// Using the brackets notation
const name = receipt['name'];
Please note that the bracket notation could be useful if you have a property name with special characters (a dot for example).
π Get a nested property
Most of the time, your objects will be more complex than the previous example. You will have nested objects, maybe nested arrays, with optional and required properties.
To get a deeper property in your object, you can use the chaining operator, the optional chaining, and the brackets. Here are some examples:
const receipt = {
icon: 'πͺ',
name: 'Cookie',
difficulty: 1,
ingredients: {
fresh: ['π₯', 'π₯'],
dry: ['π«', 'π§'],
},
comments: [
{
id: 1,
content: 'Tasty!',
},
{
id: 2,
content: 'Love it β€οΈ',
},
],
};// Chaining operator in objects
receipt.ingredients.fresh;
=> ['π₯', 'π₯']// Chaining operator in array
receipt.comments[0].content;
=> 'Tasty!'// Optional chaining
receipt.comments[3]?.content;
=> undefined// Optional chaining with default value
receipt.comments[3]?.content ?? null;
=> null
π Get all keys of an object
Sometimes you need to have an array of all the property names (= keys) at the first level of an object, there is a simple helper:
const receipt = {
icon: 'πͺ',
name: 'Cookie',
difficulty: 1,
ingredients: {
fresh: ['π₯', 'π₯'],
dry: ['π«', 'π§'],
}
};Object.keys(receipt);
=> ['icon', 'name', 'difficulty', 'ingredients'];
If you need to have all keys of a second level, you need to specify it:
const receipt = {
icon: 'πͺ',
name: 'Cookie',
difficulty: 1,
ingredients: {
fresh: ['π₯', 'π₯'],
dry: ['π«', 'π§'],
}
};Object.keys(receipt.ingredients);
=> ['fresh', 'dry'];
π Get all values of an object
Now, this is the way to have an array of all the property values of an object:
const receipt = {
icon: 'πͺ',
name: 'Cookie',
difficulty: 1,
ingredients: {
fresh: ['π₯', 'π₯'],
dry: ['π«', 'π§'],
}
};Object.values(receipt);
=> ['πͺ', Cookie', 1, {
fresh: ['π₯', 'π₯'],
dry: ['π«', 'π§'],
}];
πͺ΄ Merge two objects into a new one
Taking two objects to create a new one can become a need at some point, here is how to do:
const receipt = {
icon: 'πͺ',
name: 'Cookie',
difficulty: 1,
};const receiptDates = {
createdAt: '2022-03-04',
updatedAt: '2022-06-09',
}// With spread operator:
const receiptWithDates = {
...receipt,
...receiptDates,
};// With Object assign:
const receiptWithDates = Object.assign(receipt, receiptDates);
If the same property is on the two objects, The one from the last object will give the value:
const receipt = {
icon: 'πͺ',
name: 'Cookie',
difficulty: 1,
};const metaDatas = {
difficulty: 2,
}// With spread operator:
const receiptWithMetas = {
...receipt,
...metaDatas,
};receiptWithMetas.difficulty
=> 2
π» Conclusion
As you probably saw, manipulating objects in Javascript is pretty simple and you can find multiple ways to do the same things.
I hope you liked this quick guide, donβt hesitate to π the article if you found it interesting!