Compact Objects in JavaScript
Last Updated :
02 Jul, 2024
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:
Using Object Literals
Object 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.
JavaScript
function createCompObj(obj) {
const compObj = {};
Object.keys(obj).forEach(key => {
const value = obj[key];
if (value !== null && value !== undefined && value !== false) {
compObj[key] = value;
}
});
return compObj;
}
const originalObj = {
name: 'GFG',
age: 50,
city: null,
state: undefined,
active: false,
country: 'INDIA'
};
const compObj = createCompObj(originalObj);
console.log(compObj);
Output{ name: 'GFG', age: 50, country: 'INDIA' }
Using a simple for...in loop
This 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`.
JavaScript
function compactObject(obj) {
const result = {};
for (const key in obj) {
if (obj[key]) {
result[key] = obj[key];
}
}
return result;
}
const originalObject = {
name: "geek",
age: 23,
isActive: false,
address: null,
email: "[email protected]",
phone: undefined,
score: NaN
};
const compactedObject = compactObject(originalObject);
console.log(compactedObject);
Using Lodash _.pickBy method
This 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.
JavaScript
const _ = require('lodash');
const originalObject = {
name: "geek",
age: 0,
isActive: false,
address: null,
email: "[email protected]",
phone: undefined,
score: NaN,
div: "A"
};
const compactedObject = _.pickBy(originalObject, value => value);
console.log(compactedObject);
Output:
{ name: 'geek', email: '[email protected]', div: 'A' }
Similar Reads
JavaScript Text Formatting JavaScript has many inbuilt features to format the text. Texts are the strings in JavaScript. There are many formatting styles like making text uppercase, lowercase, bold, and italic. Below are several formatting styles in JavaScript which are as follows: Table of Content Making text UpperCaseMaking
2 min read
JavaScript Online Compiler The JavaScript (JS) Online Compiler and Editor is a free online tool providing an integrated development environment (IDE) for creating and executing JavaScript code. Whether you are a beginner looking to learn JavaScript or an experienced developer want to test snippets of code quickly, an online c
3 min read
Compressing String in JavaScript Compressing a string involves replacing repeated characters with their count followed by the character itself. For example, string aaabbccc can be compressed to 3a2b3c. Examples:Input: string = aaabbbcccOutput: compressed string = 3a3b3c Input: string = heeeeellllllooooooOutput: compressed string =
2 min read
JavaScript Function Complete Reference A JavaScript function is a set of statements that takes inputs, performs specific computations, and produces outputs. Essentially, a function performs tasks or computations and then returns the result to the user.Syntax:function functionName(Parameter1, Parameter2, ..) { // Function body}Example: Be
3 min read
Introduction to JavaScript JavaScript is a versatile, dynamically typed programming language used for interactive web applications, supporting both client-side and server-side development, and integrating seamlessly with HTML, CSS, and a rich standard library.JavaScript is a single-threaded language that executes one task at
7 min read
Nesting For Loops in JavaScript Nesting for loops is crucial in JavaScript, enabling iteration over multi-dimensional data structures or performing complex tasks. It involves placing one loop inside another, where the outer loop executes for each iteration of the inner loop. This facilitates operations on multi-dimensional arrays
4 min read