【问题标题】:Typescript join specific properties of an array as string打字稿将数组的特定属性连接为字符串
【发布时间】:2018-06-11 15:15:18
【问题描述】:

我有一个 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
        }
      ]
    }
  ]
}

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

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

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

【问题讨论】:

    标签: arrays typescript


    【解决方案1】:

    大概是这样的:

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

    https://jsfiddle.net/ernmtcgj/

    【讨论】:

      【解决方案2】:

      您可以将数据简化为一个数组,然后加入该数组

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

      【讨论】:

        猜你喜欢
        • 2019-12-07
        • 2023-01-19
        • 1970-01-01
        • 2021-03-21
        • 2016-05-28
        • 1970-01-01
        • 2022-01-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多