How to get a subset of JavaScript object's properties?



Let’s say the following is our object −

var details ={
   firstName: "John",
   lastName: "Smith",
   age:21,
   subjectName:"JavaScript",
   marks:89,
   coutryName:"US",
   collegeName:"MIT",
   passoutYear:2018
};

Following is the code to fetch only a subset −

Example

var details ={
   firstName: "John",
   lastName: "Smith",
   age:21,
   subjectName:"JavaScript",
   marks:89,
   coutryName:"US",
   collegeName:"MIT",
   passoutYear:2018
};
var selectedFieldFromObjectDetails = (({ firstName,
subjectName,marks,passoutYear }) => ({ firstName,
subjectName,marks,passoutYear }))(details);
console.log(selectedFieldFromObjectDetails);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo120.js.

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo120.js{
   firstName: 'John',
   subjectName: 'JavaScript',
   marks: 89,
   passoutYear: 2018
}
raja
Published on 09-Sep-2020 13:53:52
Advertisements