Killer Beast
Killer Beast

Reputation: 177

Typescript join specific properties of an array as string

I have an API that gives me a response of something like this:

{
  "item": [
    {
      "_id": "5a48e0c100a5863454c0af2a",
      "name": "Maths",
      "created_by": "5a43ee3231ad5a6b0850d961",
      "__v": 0,
      "created_on": "2017-12-31T13:06:09.957Z",
      "active": 1,
      "grade": [],
      "syllabus": [
        {
          "_id": "5a47a5faed12d92d0c2449f4",
          "name": "CBSE",
          "description": "CBSE Syllabus",
          "created_by": "5a43ee3231ad5a6b0850d961",
          "__v": 0,
          "created_on": "2017-12-30T14:43:06.305Z",
          "banner": 1,
          "active": 1
        },
        {
          "_id": "5a47a615ed12d92d0c2449f5",
          "name": "State Board",
          "description": "State Board Syllabus",
          "created_by": "5a43ee3231ad5a6b0850d961",
          "__v": 0,
          "created_on": "2017-12-30T14:43:33.328Z",
          "banner": 1,
          "active": 1
        }
      ]
    }
  ]
}

As you can see, there is an item named maths in the array of item. Now inside the maths, we have another array of syllabus. I want to join the names of all the syllabus of maths. In simple terms, say I want to do something like this:

array element 1 - maths - CBSE, State Board
array element 2 - chemistry - CBSE, State Board

AFAIK, we can't do it without 2 forEach loops. Is there any better way to deal with this situation?

Upvotes: 4

Views: 9482

Answers (2)

Daniel Khoroshko
Daniel Khoroshko

Reputation: 2721

Probably like this:

  const result = item.map(it => ({
      name: it.name,
      syllabi: it.syllabus.map(s => s.name).join(', ')
    }));

https://jsfiddle.net/ernmtcgj/

Upvotes: 8

baao
baao

Reputation: 73241

You could reduce the data to an array, then join that

let obj = {"item": [{"_id": "5a48e0c100a5863454c0af2a","name": "Maths","created_by": "5a43ee3231ad5a6b0850d961","__v": 0,"created_on": "2017-12-31T13:06:09.957Z","active": 1,"grade": [],"syllabus": [{"_id": "5a47a5faed12d92d0c2449f4","name": "CBSE","description": "CBSE Syllabus","created_by": "5a43ee3231ad5a6b0850d961","__v": 0,"created_on": "2017-12-30T14:43:06.305Z","banner": 1,"active": 1},{"_id": "5a47a615ed12d92d0c2449f5","name": "State Board","description": "State Board Syllabus","created_by": "5a43ee3231ad5a6b0850d961","__v": 0,"created_on": "2017-12-30T14:43:33.328Z","banner": 1,"active": 1}]}]};

let l = obj.item.reduce((a, {name, syllabus}) =>
    [name].concat(syllabus.map(({name}) => name))
, []);

console.log(l);
console.log(`${l.shift()} - ${l.join(', ')}`); 

Upvotes: 0

Related Questions