Extract properties from an object in JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

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' }
raja
Published on 26-Aug-2020 14:50:07
Advertisements