【发布时间】:2017-03-17 02:51:31
【问题描述】:
我有这段代码,我一直在反复试验:
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'
我想要的是能够从函数外部访问surveyAnswerMatches 数组。我认为返回数组将允许我通过 _fk 变量访问它。
为什么返回值没有赋值给_fk?
什么可以让我从所有 .forEach 和 .map 调用之外访问surveyAnswerMatches?
感谢 SO 社区!
编辑:更多信息
console.log('this.selectedIaReportDiscussedTopic$', this.selectedIaReportDiscussedTopic$) //[{_id: "discussed_topic_2016-11-03T11:48:48Z_1", fk_surveyanswer:"surveyanswer_2016-11-03T11:48:48Z_1" }]
let surveyAnswerMatches = this.selectedIaReportDiscussedTopic$
.map((discussionTopic) => {return discussionTopic.fk_surveyanswer})
.map((fk) => {
return this.surveyAnswers.filter((sa) => {
return fk === sa._id
})
});
console.log('this is surveyAnswerMatches', surveyAnswerMatches)// This is what I get [[{_id:"surveyanswer_2016-11-03T11:48:48Z_1", foo: "someotherbar"}]]
console.log('this.surveyAnswers', this.surveyAnswers)// [{_id:"surveyanswer_2016-11-02T13:29:26Z_1", foo: "bar"}, {_id:"surveyanswer_2016-11-02T15:34:41Z_1", foo: "somebar"},{_id:"surveyanswer_2016-11-03T11:48:48Z_1", foo: "someotherbar"}]
【问题讨论】:
-
代码的总体目标是什么?
-
我的目标是返回surveyAnswerMatches 数组中的内容。我有多个状态对象,我需要根据foreign_keys 在其中的一些对象之间进行映射。
-
您想要一个包含所有
surveyAnswerMatches数组的所有成员的数组吗?或者你想要一个数组?如果是前者,请使用.reduce()。如果是后者,请按照下面@T.J.Crowder 的建议使用.map()。如果您只想要第一个surveyAnswerMatches数组,请使用.find()。答案取决于对问题的清晰解释。 -
“我的目标是返回surveyAnswerMatches 数组中的内容。” 再说一次,哪个?在上面,每个调用都有一个回调。
-
@T.J.Crowder 我在我的问题中包含了更多信息,并且还切换到使用您在回答中提到的 .map 方法。我想我最终得到一个数组数组的原因是因为我调用了 .map()。如果我只想要一个surveyanswers 对象数组,我可以使用.concat()。我会试试看!
标签: javascript arrays typescript functional-programming