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
How to get a subset of a javascript object's properties?
To get a subset of an object's properties and create a new object with selected properties, you can use object destructuring combined with property shorthand. This technique allows you to extract specific properties and create a new object containing only those properties.
Basic Example
Let's start with an object containing multiple properties:
const person = {
name: 'John',
age: 40,
city: 'LA',
school: 'High School'
};
// Extract only name and age
const {name, age} = person;
const selectedObj = {name, age};
console.log(selectedObj);
{ name: 'John', age: 40 }
Method 1: Destructuring with Property Shorthand
The most concise approach combines destructuring and property shorthand in one line:
const person = {
name: 'Alice',
age: 25,
email: 'alice@example.com',
phone: '123-456-7890',
address: 'New York'
};
// Create subset with name, email, and phone
const subset = (({name, email, phone}) => ({name, email, phone}))(person);
console.log(subset);
{ name: 'Alice', email: 'alice@example.com', phone: '123-456-7890' }
Method 2: Using Object.pick Function
For reusability, create a helper function that picks specific properties:
function pick(obj, keys) {
return keys.reduce((result, key) => {
if (key in obj) {
result[key] = obj[key];
}
return result;
}, {});
}
const user = {
id: 1,
username: 'johndoe',
password: 'secret123',
email: 'john@example.com',
createdAt: '2023-01-01'
};
// Pick only safe properties to send to client
const publicUser = pick(user, ['id', 'username', 'email']);
console.log(publicUser);
{ id: 1, username: 'johndoe', email: 'john@example.com' }
Method 3: Using Rest Operator to Exclude Properties
Sometimes it's easier to exclude specific properties rather than include them:
const apiResponse = {
data: 'important info',
status: 200,
timestamp: '2023-12-01',
internalId: 'xyz123',
debugInfo: 'sensitive data'
};
// Exclude internal properties
const {internalId, debugInfo, ...publicData} = apiResponse;
console.log(publicData);
{ data: 'important info', status: 200, timestamp: '2023-12-01' }
Comparison
| Method | Best For | Readability | Reusability |
|---|---|---|---|
| Destructuring + Shorthand | Few properties, one-time use | High | Low |
| Pick function | Dynamic property selection | Medium | High |
| Rest operator (exclusion) | Excluding few properties | High | Medium |
Conclusion
Object destructuring with property shorthand is the most common approach for creating object subsets in JavaScript. For dynamic scenarios, use a pick function, and when you need to exclude only a few properties, the rest operator provides an elegant solution.
