Home > Enterprise >  Express.js Typescript: How to send only some of the properties of all the objects in an array throug
Express.js Typescript: How to send only some of the properties of all the objects in an array throug

Time:08-26

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.

CodePudding user response:

make a new list of objects to send back via express response. So in the handler:

personArray = [new Person("Susan",25,170), new Person("Peter",23,220)];
let newPersonArray = personaArray.map((item) => {
   return {
    name: item.name,
    age: item.age,
    // any more properties you want returned you can add them here.
  }
})
return newPersonArray;

CodePudding user response:

You can do it like so:

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

Which, in this case, can be done inside map, foreach.

You can encapsulate this logic, or a manual mapping, 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.

CodePudding user response:

Provide a toJSON method that determines how the object gets converted to JSON.

class Foo {
  constructor(a, b, c) {
    this.a = a;
    this.b = b;
    this.c = c;
  }
  toJSON() {
    return {
      a: this.a,
      c: this.c
    }
  }
}

const data = [new Foo(1, 2, 3), new Foo(4, 5, 6)];

const json = JSON.stringify(data);

console.log(json);

This assumes that you want to transform your objects like that consistently. If you need to extract the data in this particular case then you'll need to generate the objects you pass to JSON.stringify outside of the class.

  • Related