如何使用map()函数分配数组对象属性?

时间:2019-06-13 14:49:54

标签: javascript typescript

我有这样的课

export class CompetitionModel{
  id: number;
}

export class Competition{
  competitionNumber: number;
}

let  competitions1= [{id:10},{id:20},{id:30}  ];

let  competitions2: Competition[];

我想将CompetitionModel.id分配给Competition.competitionNumber,但使用map()而不使用forforeach

我怎样才能成功?

在地图函数的结尾,我希望competitions2等于

[{competitionNumber:10},{competitionNumber:20},{competitionNumber:30}  ];

2 个答案:

答案 0 :(得分:1)

您可以像这样简单地使用map函数。

competitions2 = competitions1.map(c => ({competitionNumber: c.id}));

Demo

或者...

competitions2 = competitions1.map(c => {
  const comp = new Competition();
  comp.competitionNumber = c.id;
  return comp;
});

Demo

答案 1 :(得分:-2)

我不为此使用地图,但是我会在获得示例后立即更新这篇文章。现在:

arr = [{id:123 ... },{id:432},{id:5}]

// finds a single result
theObject = arr.find(obj => obj.id == 5);

// return an array of all matching results
arrayOfResults = arr.filter(obj => obj.name === 'jo');