Typescript将数组的特定属性作为字符串连接起来

时间:2018-01-01 18:16:25

标签: arrays typescript

我有一个API,可以给出类似这样的回复:

{
  "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
        }
      ]
    }
  ]
}

如您所见,maths数组中有一个名为item的项目。现在在数学中,我们有另一个syllabus数组。我想加入maths所有教学大纲的名称。简单来说,我想做这样的事情:

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

AFAIK,如果没有2个forEach循环,我们就无法做到。有没有更好的方法来处理这种情况?

2 个答案:

答案 0 :(得分:1)

可能是这样的:

file:path

https://jsfiddle.net/ernmtcgj/

答案 1 :(得分:0)

您可以将数据缩减为数组,然后加入



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(', ')}`);