Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Extract properties from an object in JavaScript
We have to write a JavaScript function, say extract() that extracts properties from an object to another object and then deletes them from the original object.
For example ?
If obj1 and obj2 are two objects, then
obj1 = {color:"red", age:"23", name:"cindy"}
obj2 = extract(obj1, ["color","name"])
After passing through the extract function, they should become like ?
obj1 = { age:23 }
obj2 = {color:"red", name:"cindy"}
Therefore, let's write the code for this function ?
Syntax
const extract = (obj, ...keys) => {
// Create new object for extracted properties
// Delete specified keys from original object
// Return new object with extracted properties
};
Example: Basic Property Extraction
const obj = {
name: "Rahul",
job: "Software Engineer",
age: 23,
city: "Mumbai",
hobby: "Reading books"
};
const extract = (obj, ...keys) => {
const newObject = Object.assign({});
Object.keys(obj).forEach((key) => {
if(keys.includes(key)){
newObject[key] = obj[key];
delete obj[key];
};
});
return newObject;
};
console.log("Extracted properties:", extract(obj, 'name', 'job', 'hobby'));
console.log("Remaining object:", obj);
Extracted properties: { name: 'Rahul', job: 'Software Engineer', hobby: 'Reading books' }
Remaining object: { age: 23, city: 'Mumbai' }
Example: Extract with Array Parameter
const user = {
id: 1,
username: "john_doe",
email: "john@example.com",
password: "secret123",
role: "admin"
};
const extractFromArray = (obj, keysArray) => {
const extracted = {};
keysArray.forEach(key => {
if (key in obj) {
extracted[key] = obj[key];
delete obj[key];
}
});
return extracted;
};
const sensitiveData = extractFromArray(user, ["password", "email"]);
console.log("Sensitive data:", sensitiveData);
console.log("Safe user object:", user);
Sensitive data: { password: 'secret123', email: 'john@example.com' }
Safe user object: { id: 1, username: 'john_doe', role: 'admin' }
Alternative Method: Using Object Destructuring
const product = {
id: 101,
name: "Laptop",
price: 999,
category: "Electronics",
inStock: true
};
const extractUsingDestructuring = (obj, keys) => {
const extracted = {};
const remaining = { ...obj };
keys.forEach(key => {
if (key in remaining) {
extracted[key] = remaining[key];
delete remaining[key];
}
});
// Update original object
Object.keys(obj).forEach(key => delete obj[key]);
Object.assign(obj, remaining);
return extracted;
};
const metadata = extractUsingDestructuring(product, ["id", "category"]);
console.log("Extracted metadata:", metadata);
console.log("Product details:", product);
Extracted metadata: { id: 101, category: 'Electronics' }
Product details: { name: 'Laptop', price: 999, inStock: true }
Comparison
| Method | Modifies Original? | Parameter Type | Use Case |
|---|---|---|---|
| Rest Parameters (...keys) | Yes | Individual strings | Known property names |
| Array Parameter | Yes | Array of strings | Dynamic property lists |
| Destructuring Approach | Yes | Array of strings | Immutable-style operations |
Key Points
The extract function is useful for:
- Separating sensitive data from public object properties
- Creating specialized objects from larger data structures
- Data transformation and cleanup operations
- Implementing object property filtering
Conclusion
The extract function provides a clean way to move properties between objects while modifying the original. Use rest parameters for simple cases or array parameters for dynamic property extraction.
Advertisements
