2016-11-03 73 views
-2

回来时,我有这样的代码,我一直在通过试错搞清楚:从.filter嵌套.ForEach

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

什么是代码的总体目标? –

+0

我的目标是在surveyAnswerMatches数组中返回whats。我有多个状态对象,我需要根据foreign_keys在它们之间进行映射。 –

+2

您想要所有'surveyAnswerMatches'数组的所有成员的单个数组?或者你想要一个数组阵列?如果前者使用'.reduce()'。如果是后者,按照下面的@ T.J.Crowder的建议使用'.map()'。如果您只想要第一个'surveyAnswerMatches'数组,请使用'.find()'。答案取决于对问题的明确解释。 –

回答

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); 

编辑:清理代码

1

How come the return value does not get assigned to _fk?

因为你进入forEach回调的返回值的绝对没有什么forEach回报做(这是什么,因此使用它的返回值给你undefined)。

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

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