Search code examples
javascriptjsontypescriptangulartypescript1.8

How to take a list of Objects and create a JSON of specific properties of the objects in the list?


I have a list that looks like this:

[ Person({ getName: Function, id: '310394', age: 30 }), Person({ getName: Function, id: '244454', age: 31 })...]

and now I want to make it like this:

{
    peopleIds: [
         244454,244454...
  ]
}

I did something like this:

public makePeopleIdJSON(list: Person[]):void {
    list.forEach(x => console.log(x.id))
  }

that just prints the id for each object in the list, but how do I make the output a json as requested above..?

thanks allot


Solution

  • Here it is :

    interface Person{
        id: string;
    }
    function makePeopleIdJSON(list: Person[]) {
        return {
            personIds: list.map(x => x.id)
        }
    }