Express.js Typescript: How to send only some of the properties of all the objects in an array through res.json()

Issue

Suppose I have an array of Persons with 3+ properties (e.g. name,age,height… and more), e.g.:

personArray = [new Person("Susan",25,170), new Person("Peter",23,220)];

And suppose I need to send over only some of the Person properties of all Persons through express.js res.json function, what is the most elegant way to write it in Typescript, so that the content in res.json() will be sent in this format?

{
 "persons":[
    {
      "name":"Susan",
      "age":25
    },
    {
      "name":"Peter",
      "age":23
    },
    ...
  ]
}

Please assume that there could be like 10+ properties and we need like only 5 to send over in res.json.
To make things clear here I use only three total fields (name, age, height) and only two fields (name & age) to send over.
And yes all Persons in the Array needed to be sent over.

Solution

You can do it like so:

let { firstName, age, ...props } = person;
let newObj = { firstName, age };

In this case, it’s done for only a person. To change the entire array, it can be done inside map, for, or your looping method of choice.

You can encapsulate this logic (or other method of mapping, like from other answers) in a DTO class (PersonWithNameAndAgeDTO) with a constructor that accepts a Person┬╣, then map only what you want.

┬╣ Or, equivalently, have an empty constructor (or whatever you need), and a method which does the mapping with a Person.

Answered By – user19513069

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published