简体   繁体   English

如何在 forEach 循环和 if 语句中正确返回字符串?

[英]How to properly return string in forEach loop and if statement?

I've been on a project, and I'm stuck with returning a string.我一直在做一个项目,但我一直在返回一个字符串。

Now let me present you the code:现在让我向您展示代码:

export const returnAsString = (
  test: Array<TestQuestionAndAnswer>
) => {
  test.forEach((response) => {
    const fetchQuestion = getQuestionBasedOnId(response.questionId)
    fetchQuestion?.question.responses.forEach((res) => {
      if (
        res.responseId == response.responseId &&
        fetchQuestion.question.id == response.questionId
      ) {
        return `
        Question: ${fetchQuestion.question.text},
        Response: ${res.text}
        `
      }
    })
  })
}

Now this function should do next: inputed test is an array containing objects with key value pairs: questionId: id, responseId: id .现在这个 function 下一步应该做:输入的test是一个包含键值对对象的数组: questionId: id, responseId: id I'm finding the texts of both by sending questionId into one function, and returning it's text, and later on comparing it with id in the test array.我通过将 questionId 发送到一个 function 并返回它的文本,然后将其与测试数组中的 id 进行比较来找到两者的文本。 Now I need to return the whole test in this form:现在我需要以这种形式返回整个测试:

question: text, response: text
//new line
question: text, response: text
//new line
etc..

and i don't know how to do this.我不知道该怎么做。 I'm getting the values but i can't get one whole string.我得到了值,但我无法得到一整串。 When I console.log this function it returns undefined, but if i console.log any of these text, it's working but it's overwriting:当我console.log这个 function 它返回未定义,但如果我console.log任何这些文本,它正在工作,但它被覆盖:

question 1,
response 1
//each line new output, overwriting old one
question 2,
response 2
question 3,
response 3
etc..

So my question is how to return one whole string?所以我的问题是如何返回一个完整的字符串? I'm expecting something like this:我期待这样的事情:

question: question1, response: response1
question: question2, response: response2
question: question3, response: response3
...

But not string overwriting each other, just only one string.但不是字符串相互覆盖,只有一个字符串。 with multiple question/responses.有多个问题/回答。

EDIT:编辑:

This is how I did returned value, but the problem is returning first undefined then values undefined value1 value2..这就是我返回值的方式,但问题是首先返回未定义的值,然后返回undefined value1 value2..

export const returnAsString = (
  test: Array<TestQuestionAndAnswer>
) => {
  let string: any
  test.forEach((response) => {
    const fetchQuestion = getQuestionBasedOnId(response.questionId)
    fetchQuestion?.question.responses.forEach((res) => {
      if (
        res.responseId == response.responseId &&
        fetchQuestion.question.id == response.questionId
      ) {
        string = string + `
        Question: ${fetchQuestion.question.text},
        Response: ${res.text}
        `
      }
    })
  })
  return string
}

Working with arrays works just fine, but i need to return a string.使用 arrays 工作得很好,但我需要返回一个字符串。

export const returnAsString = (
  test: Array<TestQuestionAndAnswer>
) => {
  let arr = new Array();
  test.forEach((response) => {
    const fetchQuestion = getQuestionBasedOnId(response.questionId)
    fetchQuestion?.question.responses.forEach((res) => {
      if (
        res.responseId == response.responseId &&
        fetchQuestion.question.id == response.questionId
      ) {
        arr.push({
        Question: fetchQuestion.question.text,
        Response: res.text
        })
      }
    })
  })
  return arr
}

Array#forEach doesn't return anything, you should use other function here. Array#forEach不返回任何内容,您应该在此处使用其他 function。

export const returnAsString = (test: Array<TestQuestionAndAnswer>) => {
  return test
    .flatMap((response) => {
      const fetchQuestion = getQuestionBasedOnId(response.questionId);

      return fetchQuestion?.question.responses
        .filter(
          (res) =>
            res.responseId == response.responseId &&
            fetchQuestion.question.id == response.questionId
        )
        .map(
          (res) => `
        Question: ${fetchQuestion.question.text},
        Response: ${res.text}
        `
        );
    })
    .join("\n");
};

Also, assuming that there is only one res in fetchQuestion?.question.responses that satisfies this condition: res.responseId == response.responseId && fetchQuestion.question.id == response.questionId , it can be simplified:另外,假设fetchQuestion?.question.responses中只有一个res满足这个条件: res.responseId == response.responseId && fetchQuestion.question.id == response.questionId ,可以简化为:

export const returnAsString = (test: Array<TestQuestionAndAnswer>) => {
  return test
    .map((response) => {
      const fetchQuestion = getQuestionBasedOnId(response.questionId);

      const matchingResponse = fetchQuestion?.question.responses.find(
        (res) =>
          res.responseId == response.responseId &&
          fetchQuestion.question.id == response.questionId
      );

      if (matchingResponse) {
        return `
        Question: ${fetchQuestion.question.text},
        Response: ${matchingResponse.text}
        `;
      }

      return "":
    })
    .join("\n");
};

forEach isn't for returning values. forEach不是用于返回值。 What you want instead is reduce which takes an initial object and then calls a function that get's the return value of previous call and next item as argument.相反,您想要的是reduce ,它采用初始 object ,然后调用 function ,它获取上一个调用的返回值和下一个项目作为参数。

export const returnAsString = (test: Array<TestQuestionAndAnswer>) =>
    test.reduce((prev, response) => {
        const fetchQuestion = getQuestionBasedOnId(response.questionId);
        return (
            prev +
            fetchQuestion?.question.responses.reduce((prev, res) => {
                if (
                    res.responseId === response.responseId &&
                    fetchQuestion.question.id === response.questionId
                ) {
                    return `Question: ${fetchQuestion.question.text}, Response: ${res.text}\n`;
                }
                return '';
            }, '')
        );
    }, '');

This will provide the expected result but since we are dealing with strings you can simplify it a bit more with join .这将提供预期的结果,但由于我们正在处理字符串,您可以使用join将其简化一点。

export const returnAsString = (test: Array<TestQuestionAndAnswer>) =>
    test
        // Flat map the arrays of response strings to one array
        .flatMap(response => {
            const fetchQuestion = getQuestionBasedOnId(response.questionId);
            return (
                // Map responses to stirngs
                fetchQuestion?.question.responses.map(res =>
                    // Switched to ternary here
                    res.responseId === response.responseId &&
                    fetchQuestion.question.id === response.questionId
                        ? // Return one string if condition is met
                          `Question: ${fetchQuestion.question.text}, Response: ${res.text}`
                        : // Return empty string if not since we must always return something
                          '',
                ) ?? []
            );
        })
        // Filter out empty rows
        .filter(r => r)
        // Join with new lines
        .join('\n');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM