How to handle an object in JavaScript with example

  • javascript
  • 191 Views
  • 5 Min Read
  • 8 Jul 2024

In this article, you will learn how to handle objects in JavaScript. After understanding this article completely, you will have a complete understanding of object handling in JavaScript, which will make your coding journey easier. Whether you're building a web application, an API, a library, or any software at all, it's important to understand object handling.

 

Let's dive in and elevate your JavaScript skills!

 

Objects in JavaScript serve as collections of key/value pairs, accommodating properties, methods, and diverse data types like strings, numbers, and booleans.

 

Handling objects in JavaScript means that you are managing, creating, and modifying objects. The object is an important thing through which we can easily organize any type of data.

 

Alright, you will learn how to handle objects in JavaScript in the best way possible.

 
  1. Constructor Functions
  2. Object.seal() Method
  3. Object.keys() and Object.values() Methods
  4. Object.entries() Methods
  5. Adding and Removing Object Properties
  6. Object Destructuring
  7. Spread Operator
  8. Nesting Objects in JavaScript
  9. Best Practices for Object Handling in JavaScript
 
 

1. Constructor Function

 
Constructor functions in JavaScript are special functions used for creating multiple instances of objects based on a predefined blueprint or template. They allow encapsulating object creation logic and defining properties and methods that all instances share.
 
function Person(name, age) {
    this.name = name;
    this.age = age;
}

const elena = new Person('Elena', 21); // Person { name: 'Elena', age: 21 }
const john = new Person('John', 31);   // Person { name: 'John', age: 31 }
 
We define a constructor function Person with parameters name and age. Using this function with the new keyword, we create two objects, elena and john. Each object is initialized with specific name and age properties.


2. Object.seal() Method

 
Object.seal() is like putting a protective shield around your JavaScript object. It stops anyone from adding new stuff or removing things, but you can still change what's already there.
 
const person = {
    name: 'Elena',
    age: 31
};

// Sealing the object
Object.seal(person);

// Modifying existing properties
person.age = 21; //✅ Allowed

// Adding a new property (will not be allowed)
person.gender = 'Male'; //❌ Not allowed

// Removing an existing property (will not be allowed)
delete person.age; // ❌ Not allowed

console.log(person); // Output: { name: 'Elena', age: 21 }
 
In this example, after sealing the person object using Object.seal(), attempts to add new properties (gender) or remove existing properties (age) will be ignored. However, modifying existing properties (age) is still permitted.
 
Object.seal() helps you keep an object's structure in check, so its properties can't be changed unexpectedly.
 
 

3. Object.assign() Method

 
Using the Object.assign() method in JavaScript allows you to copy the values of all enumerable properties from one or more source objects to a target object. This method is commonly used for object cloning and merging.
 
const obj1 = { a: 1 };
const obj2 = { b: 2 };
const newObj = Object.assign(obj1, obj2, { c: 3 });

console.log(newObj); // { a: 1, b: 2, c: 3}
 
In this code snippet, Object.assign() merges properties from obj1, obj2, and { c: 3 } into a new object newObj. The resulting newObj contains properties a, b, and c with their respective values.
 
 

4. Object.keys() and Object.values() Methods

 
Object.keys() and Object.values() methods in JavaScript are essential tools for accessing and manipulating object properties efficiently. 
 
  • Object.keys(): Returns an array of an object's enumerable property names.

 

  • Object.values(): Retrieves an array containing the values of the object's properties.
 
JavaScript development workflows can be enhanced by using these methods to navigate and manipulate object data in a seamless manner.
 
const person = {
    name: 'Elena',
    age: 21,
    city: 'New York'
};

// Retrieve an array of keys from the person object
const keys = Object.keys(person);

// Retrieve an array of values from the person object
const values = Object.values(person);

console.log(keys); // Output: ['name', 'age', 'city']
console.log(values); // Output: ['Elena', '21', 'New York']
 
The Object.keys() method is used to retrieve an array containing the keys of the person object (name, age, and city).
 
The Object.values() method is used to retrieve an array containing the values of the person object (Elena, 21, and New York).
 
 

5. Object.entries() Method

 
The Object.entries() method in JavaScript simplifies object handling by converting properties into arrays of key-value pairs. This easy method helps you handle and change data in objects, making development tasks smoother and keeping your code neat.
 
Returns an array of arrays, each containing a key-value pair of the object.
 
const person = {
    name: 'Elena',
    age: 21,
    city: 'New York'
};

const keys = Object.entries(person);
console.log(keys); // Output: [['name', 'Elena'], ['age', 21], ['city', 'New York']]
 
In this example, the Object.entries() method transforms the properties of the person object into an array format consisting of key-value pairs. For instance, [['name', 'Elena'], ['age', 21], ['city', 'New York']]. This array structure simplifies property access and manipulation tasks in JavaScript, offering a more intuitive way to work with object data.
 
 

6. Adding and Removing Object Properties

 
Adding and removing object properties in JavaScript involves dynamically modifying the properties of an object, either by adding new properties or removing existing ones.
 
// Define an object
let person = {
    name: 'John',
    age: 30,
    city: 'New York'
};

// Adding a new property
person.gender = 'Male';

// Removing an existing property
delete person.city;

console.log(person); // Output: { name: 'John', age: 30, gender: 'Male' }
 
In this example, it starts with an object person with properties name, age, and city. Then, it adds a new property gender with the value 'Male' using direct property assignment. The code also removes the city property using the delete operator. Finally, the modified person object is logged to the console.
 
 

7. Object Destructuring

 
Using Object.entries() along with object destructuring makes working with objects easier. It breaks down key-value pairs into variables, so you can easily access the keys and values of objects. This makes your code easier to read and more efficient.
 
// Define an object
const person = {
    name: 'Elena',
    age: 21,
    city: 'New York'
};

// Destructure object entries
for (const [key, value] of Object.entries(person)) {
    console.log(`${key}: ${value}`); // name: Elena age: 21 city: New York
}
 
In this code, we use object destructuring with Object.entries() to iterate over the key-value pairs of the person object. Each pair is logged to the console, allowing for easy access to both keys and values within the object.
 
 

8. Spread Operator

 
The spread operator (...) in JavaScript is a useful tool for unpacking arrays or objects, and spreading them into separate elements. When used with objects, it helps copy properties from one object to another, basically making a shallow copy.
 
// Define an object
const person = {
    name: 'John',
    age: 30,
    city: 'New York'
};

// Additional information
const info = {
    email: "elena@gmail.com"
};

// Create a new object by spreading properties of 'person' and 'info'
const newPerson = { ...person, ...info };

console.log(newPerson); // Output: { name: 'John', age: 30, city: 'New York', email: 'elena@gmail.com' }
 
We have two objects, a person with the property name, age, and city, and info with additional data like an email address. Using the spread operator { ...person, ...info }, we combine the properties of both objects into a new object called newPerson. This results in newPerson containing properties from both person and info, including name, age, city, and email.
 
 

9. Nesting Objects in JavaScript

 
Nesting objects in JavaScript refers to the practice of including objects as values of properties within another object. This lets you make complex data structures where objects can contain other objects, creating structured connections.
 
// Define a nested object
const person = {
    name: 'Elena',
    age: 21,
    address: {
        street: '123 Main St',
        city: 'New York',
        country: 'USA'
    }
};

// Accessing nested object properties
console.log(person.name);          // Output: 'Elena'
console.log(person.address.city);  // Output: 'New York'
 
In this code example, we have demonstrated nesting objects in JavaScript. We define an object as a person with a property name, age, and address. The address property contains another object with properties street, city, and country. Accessing nested properties is achieved using dot notation, such as person.address.city to retrieve the city value.
 
 

10. Best Practices for Object Handling in JavaScript

 
  • Descriptive Property Names: Use clear and descriptive names for object properties to enhance code readability and understanding.
 
  • Modularization: Break down large objects into smaller, modular components to promote code reusability and easier maintenance.
 
  • Immutability: Prefer immutable objects whenever possible to avoid unintended side effects and facilitate predictable code behavior.
 
  • Error Handling: Implement error handling mechanisms to handle unexpected situations and ensure robustness in object interactions gracefully.
 
  • Documentation: Make easy documents on objects—what they are and what they do. Helps developers understand.
 
  • Testing: Conduct thorough testing of object functionality to verify correctness and identify potential issues early in the development process.
 
  • Performance Optimization: Optimize object handling operations for performance by avoiding unnecessary object manipulations and using efficient data structures and algorithms.
 
 

Conclusion

 
To manage objects in JavaScript, you can create, access, modify, add, delete properties, iterate through them, check for existence, and utilize object methods. Make sure to use proper names for properties and avoid directly changing objects to keep your code neat and easy to understand.
 
If you have any questions regarding this article or any other web development, then you can ask them in the question box given below, and you will get the answer as soon as possible.

Didn't find your answer? Add your question.

Share

Comments (0)

No comments yet. Be the first to comment!

About Author

Username

Poojan Joshi ( poojanjoshi )

Full Stack JavaScript Developer

Joined On 12 Apr 2024

More from Poojan Joshi

Top 60 Eye-Catching Button Designs Users Can’t Wait to Click - With Source Code

ui-ux

11 Oct 2024

Discover 60 eye-catching button designs with source code, crafted with HTML and CSS to enh....

How to Check Website Speed: Key Metrics, Tools, and Optimization Tips

web-development

21 Sep 2024

Learn how to test your website speed, key metrics to track, top tools to use, and expert o....

Everything About Debouncing Function in JavaScript: Comprehensive Guide

javascript

13 Aug 2024

Learn everything about the debouncing function such as what it is, why and where to use it....

How to Create Advanced Search Bar with Suggestions in React: A Step-by-Step Guide

react-js

2 Aug 2024

Learn to build an advanced React search bar with suggestions, highlighted text, efficient ....

How to Create a Full-Featured Todo List App Using ReactJS

react-js

19 Jul 2024

Learn how to build a powerful Todo List App using ReactJS. A step-by-step guide covering d....

How to Create a Full-Featured Todo List App Using HTML, CSS, and JavaScript

javascript

16 Jul 2024

Learn to build a feature-rich to-do list with HTML, CSS, and JavaScript. Perfect for inter....

Popular Posts from Code Mafias

10 Fun Websites for Stress Relief and Relaxation During Coding Breaks

programming

11 Nov 2024

Top 10 fun websites for coders to relax during breaks. Recharge with interactive games, ar....

Mastering HTML: Top 12 Unique HTML Tags with Examples

html

4 May 2024

Through this article, learn those essential HTML tags that many developers do not know abo....

Top 60 Eye-Catching Button Designs Users Can’t Wait to Click - With Source Code

ui-ux

11 Oct 2024

Discover 60 eye-catching button designs with source code, crafted with HTML and CSS to enh....

How to Upload Code to GitHub: Quick Steps and Detailed Instructions for Beginners

github

16 Sep 2024

In order to upload (push) your project to GitHub, it involves multiple steps that need to ....

How to install MongoDB on windows in 2024

mongodb

2 May 2024

MongoDB is a Database Management System based on NoSQL (Not Only SQL) and utilizes JSON-li....

How to Implement Undo Functionality for Deleting Items in Your React App

react-js

28 Sep 2024

Learn how to implement undo functionality for deleting items in React. Follow a step-by-st....