从嵌入.ForEach

时间:2016-11-03 13:34:43

标签: javascript arrays typescript functional-programming

我有这个代码,我一直在通过反复试验找出:

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

2 个答案:

答案 0 :(得分:1)

  

为什么返回值没有分配给_fk?

因为传递给forEach的回调的返回值与forEach返回的内容完全无关(这没什么,所以使用它的返回值会给你undefined)。

你说你想要使用“返回值”,但是哪一个?对于数组中的每个条目,重复调用一次回调。

您可以将forEach更改为另一个map,这意味着您最终会为数组中的每个条目添加一个包含surveyAnswerMatches的数组。

答案 1 :(得分:1)

在调用映射和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);

修改:清理代码