Javascript 从嵌套在.ForEach中的.filter返回
我有一个代码,我通过反复试验得出:Javascript 从嵌套在.ForEach中的.filter返回,javascript,arrays,typescript,functional-programming,Javascript,Arrays,Typescript,Functional Programming,我有一个代码,我通过反复试验得出: let _fk = this.selectedIaReportDiscussedTopic$ .map((discussionTopic) => {return discussionTopic.fk_surveyanswer}) //["string"] .forEach((fk) => { let surveyAnswerMatches = this.surveyAnswers.filte
let _fk = this.selectedIaReportDiscussedTopic$
.map((discussionTopic) => {return discussionTopic.fk_surveyanswer}) //["string"]
.forEach((fk) => {
let surveyAnswerMatches = this.surveyAnswers.filter((sa) => {
return fk === sa._id
})
console.log('surveyAnswerMatches', surveyAnswerMatches)//[object] <- this contains what I want and so I return it below, but nothing shows in console.log(_fk)
return surveyAnswerMatches
})
console.log('this is fk', _fk) //'undefined'
为什么返回值没有分配给_fk
因为您传入的回调的返回值与forEach
返回的内容完全无关(这与什么都无关,所以使用它的返回值可以得到undefined
)
你说过你想使用“返回值”,但是哪一个呢?对数组中的每个条目重复调用回调一次
您可以将您的
forEach
更改为另一个map
,这意味着您将得到一个数组,其中包含数组中每个条目的surveyanswormaches
。只需使用闭包访问在调用映射和forEach之前定义的变量:
let surveyAnswerMatches = [];
this.selectedIaReportDiscussedTopic$
.map((discussionTopic) => {return discussionTopic.fk_surveyanswer}) //["string"]
.forEach((fk) => {
surveyAnswerMatches.push(this.surveyAnswers.filter((sa) => {
return fk === sa._id;
}));
});
console.log('this is surveyAnswerMatches', surveyAnswerMatches);
编辑:清理代码代码的总体目标是什么?我的目标是返回SurveyanSwertaches数组中的内容。我有多个状态对象,需要根据外键在多个状态对象之间进行映射。是否要一个包含所有
surveyanswormaches
数组的所有成员的数组?或者你想要一个数组?如果是前者,请使用.reduce()
。如果是后者,请使用下面@T.J.Crowder建议的.map()
。如果只需要第一个调查和应答
数组,请使用.find()
。答案取决于对问题的清晰解释。“我的目标是返回surveyAnswerMatches数组中的内容。”再说一遍,是哪一个?在上面的例子中,每个回拨电话都有一个。@T.J.Crowder我在我的问题中包含了更多的信息,并切换到使用你在回答中提到的.map方法。我想我最终得到一个数组的原因是因为我调用了.map()。如果我只需要一组surveyanswers对象,我可以使用.concat()。我要试试看!
let surveyAnswerMatches = [];
this.selectedIaReportDiscussedTopic$
.map((discussionTopic) => {return discussionTopic.fk_surveyanswer}) //["string"]
.forEach((fk) => {
surveyAnswerMatches.push(this.surveyAnswers.filter((sa) => {
return fk === sa._id;
}));
});
console.log('this is surveyAnswerMatches', surveyAnswerMatches);