Our Blog:

Mastering JavaScript Objects Methods: A Comprehensive Guide


All
Andrej Vajagic

Andrej Vajagic

25.07.2023, 16:48

Read time: undefined mins

Mastering JavaScript Objects Methods: A Comprehensive Guide

Let's look at some common JavaScript object methods, with examples, to understand whether they mutate the original object and when you might use them:

1. Object.assign(target, ...sources)

  • Mutates? Yes.
  • Example: code)
  • Use When: You want to copy all enumerable own properties from one or more source objects to a target object. It's useful for merging objects or creating a shallow copy.

2. Object.create(proto, [propertiesObject])

  • Mutates? No.
  • Example: code)
  • Use When: You need to create a new object with the specified prototype object and properties. It’s a way to create objects with a specific prototype.

3. Object.freeze(obj)

  • Mutates? Yes.
  • Example: code)
  • Use When: You want to make an object immutable, preventing new properties from being added to it and existing properties from being removed or changed.

4. Object.keys(obj)

  • Mutates? No.
  • Example: code)
  • Use When: You need to get an array of a given object's own enumerable property names.

Real life example

code) In this example:

  • We start with an initialSettings object that holds the settings.
  • The SettingsForm component uses useState to manage the settings state.
  • It dynamically generates form inputs for each setting using Object.keys(settings).map(key => ...). This approach allows for the creation of different input types based on the setting's value type (e.g., checkbox for booleans, text input for strings).
  • Each input field is labeled and populated based on the settings object's keys and values. The handleInputChange function updates the state of the settings when the user changes any input, ensuring the state remains in sync with the user's input.
  • The form allows users to update their settings dynamically, with the form fields automatically adjusting to reflect the structure of the settings object.

This example demonstrates how Object.keys(obj) can be used to iterate over an object's properties, enabling dynamic UI generation based on the object's structure. This method is particularly useful for creating flexible interfaces that need to adapt to varying data shapes or configurations.

5. Object.values(obj)

  • Mutates? No.
  • Example: code)
  • Use When: You want to get an array of a given object's own enumerable property values.

Real life example

code) In this example:

  • We have a salesByCategory object that stores the total sales figures for different categories.
  • The SalesSummary component calculates the total sales by using Object.values(salesByCategory) to create an array of the sales figures and then applying .reduce() to sum these values.
  • It displays the total sales figure and also iterates over Object.entries(salesByCategory) to list sales by category, providing a detailed breakdown along with the summary.

This example demonstrates how Object.values(obj) can be utilized to work with the values of an object directly, enabling operations like calculations, summaries, or transformations. This method is particularly useful when you need to aggregate or analyze data stored in object format, providing a concise and readable way to access and manipulate this data in React components.

6. Object.entries(obj)

  • Mutates? No.
  • Example: code)
  • Use When: You need to get an array of a given object's own enumerable string-keyed property [key, value] pairs.

Real life example

code) In this example:

  • The userProfile object contains various pieces of information about the user.
  • The UserProfileDetails component uses Object.entries(userProfile) to iterate over the profile data, converting each [key, value] pair into a list item. This allows for dynamic generation of the profile details without explicitly coding each piece of information.
  • For each [key, value] pair, the key is formatted to insert a space before any uppercase letters (to improve readability of camelCase keys) and to capitalize the first letter. This makes the property names more user-friendly (e.g., "subscriptionStatus" becomes "Subscription Status").
  • The component renders an unordered list () where each list item () displays a profile attribute and its value.

This real-life example demonstrates how Object.entries(obj) is effectively used to create dynamic and flexible UI components in React that can adapt to varying data structures, allowing developers to easily iterate over objects and render their contents in a user-friendly format.

7. Object.defineProperty(obj, prop, descriptor)

  • Mutates? Yes.
  • Example: code)
  • Use When: You want to define a new property directly on an object, or modify an existing property on an object, and return the object.

Shallow vs deep copy

Creating a shallow copy or a deep copy of an object in JavaScript is important depending on what level of data duplication you need. Let's explore both:

Shallow Copy of an Object

A shallow copy copies the top-level properties of an object but not the nested objects. Nested objects are shared between the original and the copy.

Methods for Shallow Copy:

  1. Object.assign code)

  2. Spread Syntax (...) code)

Deep Copy of an Object

A deep copy duplicates everything. It creates a new instance of each object and recursively copies all nested objects.

Methods for Deep Copy:

  1. JSON.parse and JSON.stringify

    • This method works well for objects containing only properties that can be converted to JSON (no functions, circular references, etc.).
    • It's a quick and easy way to deep clone an object, but has limitations like not copying methods. code)
  2. Custom Recursive Function

    • For more complex objects (e.g., containing functions, circular references), you might need to write a custom deep cloning function.
    • This method involves recursively copying all properties of the object.
  3. MODERN: structuredClone

  • The **structuredClone&& method is a new feature in modern JavaScript that allows you to deep clone an object, including its prototype chain.

Here's how it works:

const obj = { a: 1, b: { c: 2 } };
const clonedObj = structuredClone(obj);
console.log(clonedObj); // Output: { "a": 1, "b": { "c": 2 } }

The structuredClone method is part of the Web APIs and is supported by most modern browsers. It's a more efficient and safer way to deep clone objects compared to other methods.

Here are some benefits of using structuredClone:

  • Preserves prototype chain: Unlike other methods, structuredClone preserves the original object's prototype chain.
  • Deep clones recursively: It recursively clones all nested objects and arrays.
  • Efficient: It's faster than other deep cloning methods, especially for large objects.

However, keep in mind that structuredClone is only available in modern browsers and Node.js versions 14+.

If you need to support older browsers or Node.js versions, you can use one of the other methods I mentioned earlier.

Note:

  • The JSON.parse(JSON.stringify()) method doesn't copy object methods and doesn't work with special types of objects like Date, RegExp, Map, Set, etc. For such cases, a custom or library-provided deep clone function would be more appropriate.
  • When using libraries like Lodash, you can use their deep clone functions (_.cloneDeep), which handle various edge cases and data types.

Conclusion

  • Use a shallow copy when you only need a duplicate of the top-level data and don’t modify nested objects.
  • Opt for a deep copy when you need a fully independent clone of an object, including all nested objects. However, be mindful of the performance implications, especially for large or complex objects.

Share:

Accelerating Digital Success. Experience the future of web development – faster, smarter, better. Lets innovate together.

©2024 Dreit Technologies | All rights reserved

Contact

  • +38 64 577 3034
  • Serbia
  • Marka Pericina Kamenjara 11A, Ruma
  • Contact us