![]() |
Compacting an object refers to removing properties with false values (like null, undefined, 0, false, “”, NaN, etc.). Objects are used to store collections of data and more complex entities. They can be extended and manipulated in various ways to suit different programming needs. One interesting aspect of JavaScript objects is their compact representation, which allows for efficient storage and retrieval of properties. Below are the approaches for compacting objects in JavaScript: Table of Content Using Object LiteralsObject literals let you easily create objects by listing their properties and values. They’re essential for making data structures that are simple and organized. Example: Demonstrates the creation and access of properties in a compact JavaScript object using object literals.
Output { name: 'GFG', age: 50, country: 'INDIA' } Using a simple for…in loopThis involves iterating over an object’s properties to selectively add only truthy values to a new object. It enhances data clarity and efficiency by filtering out falsy values like `null`, `undefined`, and empty strings (`”`), ensuring that the resulting object contains only meaningful data points. It’s a concise and effective method for optimizing object structures while maintaining code simplicity and performance. Example: This function `compactObject` filters truthy properties from `originalObject` into `compactedObject`, omitting falsy values like `false`, `null`, `undefined`, empty strings, and `NaN`.
Output { name: 'geek', age: 23, email: '[email protected]' } Using Lodash _.pickBy methodThis method helps create smaller objects by selecting properties based on a given rule. It goes through all properties of an object, including ones it inherits, and makes a new object with only the properties that meet the rule. This is great for removing properties with values like `null`, `undefined`, `false`, `0`, `NaN`, or empty strings (`”`), or any other specific condition. Example: :This illustrates Lodash’s `_.pickBy` to create `compactedObject` by filtering out falsy values from `originalObject`, ensuring the resulting object contains only truthy properties.
Output: { name: 'geek', email: '[email protected]', div: 'A' } |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 20 |