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 }
Updated on: 2020-09-09T13:55:30+05:30

175 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements