Skip to content Skip to sidebar Skip to footer

Filter Array By Nested Value That Meets Certain Condition In Vue

I am trying to filter an Array that contains nested array of Objects. I would like for the v-for to only show those objects that meet certain condition. I have created a JSfiddle C

Solution 1:

You're filtering the engagements based on them having 1 or more unanswered questions, but the v-for is still rendering all questions inside those engagements.

WRONG: Add v-if="question.answered==0" to the <li> element to only show unanswered questions. (This is wrong practice, I found out: see lint error here. You should not use v-if and v-for on the same element.)

CORRECT: In this case extend your filteredQuestions computed value function to only return questions without answers. (Now you are just filtering the engagements based on that, but still returning all of the questions.)

Your computed value function could be:

filteredQuestions() {
    returnthis.engagements// Return a modified copy of engagements..
        .map((engagement) => {
            // ..with all answered questions filtered out..
            engagement.questions = engagement.questions.filter((question) => question.answered === 0);
            return engagement;
        })
        // ..and only return engagements that have (unanswered) questions left
        .filter((engagement) => engagement.questions.length !== 0);
}

Solution 2:

The above option not work if you are trying to find the first level's array and nested item in array

For example engagements's name and questions sub item name because the filter will do the last match

If you are trying to find matches on nested array for example on names should do the next code

returnthis.content.filter((sub) => {
      //for save the status
      let show = false//find in nested: themes
      sub.Themes = sub.Themes.filter((theme) => {
        if (reg.test(theme.name)) {
          show = truereturntrue
        }
        returnfalse
      })
      //if was finded match in themes show the subject or if the subject name match tooif (show === true || reg.test(sub.name)) {
        returntrue
      }
      returnfalse
    })

Post a Comment for "Filter Array By Nested Value That Meets Certain Condition In Vue"