- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
Example
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(extract(obj, 'name', 'job', 'hobby')); console.log(obj);
Output
The output in the console will be −
{ name: 'Rahul', job: 'Software Engineer', hobby: 'Reading books' } { age: 23, city: 'Mumbai' }
- Related Articles
- Remove number properties from an object JavaScript
- Extract key value from a nested object in JavaScript?
- JavaScript Object Properties
- Shortest syntax to assign properties from function call to an existing object in JavaScript
- Extract unique values from an array - JavaScript
- Returning the highest number from object properties value – JavaScript
- What are the properties of an array object in JavaScript?
- How to add properties and methods to an object in JavaScript?
- How to create an object and access its properties in JavaScript?
- How to duplicate Javascript object properties in another object?
- How to add properties and methods to an existing object in JavaScript?
- How to create object properties in JavaScript?
- How to delete object properties in JavaScript?
- Merge and group object properties in JavaScript
- Filter the properties of an object based on an array and get the filtered object JavaScript

Advertisements