In JavaScript, you can create a subset of an object by selecting only the required properties. This is useful for extracting specific data without modifying the original object.
- Use object destructuring to select specific properties.
- Use Object.entries() with filter() for dynamic property selection.
- Use Lodash's _.pick() when working with multiple selected properties.
Approach 1: Using Object Destructuring
Object destructuring allows you to extract specific properties from an object and create a new object containing only those properties.
const obj = {
property1: 5,
property2: 6,
property3: 7
};
const { property1, property3 } = obj;
const subset = {
property1,
property3
};
console.log(subset);
Output
{ property1: 5, property3: 7 }
Syntax:
const { property1, property3 } = obj;
const subset = {
property1,
property3
};
Approach 2: Using Object.entries() and filter()
Object.entries() converts the object into an array of key-value pairs. The filter() method can then select only the required properties, and Object.fromEntries() converts them back into an object.
const obj = {
name: "John",
age: 25,
city: "Delhi",
country: "India"
};
const requiredKeys = ["name", "city"];
const subset = Object.fromEntries(
Object.entries(obj).filter(([key]) =>
requiredKeys.includes(key)
)
);
console.log(subset);
Output
{ name: 'John', city: 'Delhi' }
Syntax:
Object.fromEntries(
Object.entries(obj).filter(([key]) =>
requiredKeys.includes(key)
)
);
Approach 3: Using Object.keys() and reduce()
Object.keys() returns the object's property names, while reduce() can be used to build a new object containing only the selected properties.
const obj = {
name: "John",
age: 25,
city: "Delhi",
country: "India"
};
const requiredKeys = ["name", "country"];
const subset = requiredKeys.reduce((result, key) => {
if (key in obj) {
result[key] = obj[key];
}
return result;
}, {});
console.log(subset);
Output
{ name: 'John', country: 'India' }
Approach 4: Using Lodash _.pick()
Lodash provides the _.pick() method to create a new object containing only the specified properties.
const _ = require("lodash");
const obj = {
name: "John",
age: 25,
city: "Delhi",
country: "India"
};
const subset = _.pick(obj, ["name", "city"]);
console.log(subset);
Output:
{ name: 'John', city: 'Delhi' }Syntax:
_.pick(object, [paths]);Note: For a small, fixed set of properties, object destructuring is concise and readable. For dynamically selecting properties, Object.entries() with filter() is generally more flexible.