如何在计算数据(VueJS)中过滤嵌套数据?

时间:2018-08-02 15:42:14

标签: javascript vuejs2

这个想法很简单。

在一个计算变量中,我想使用needle来过滤部分,而不是仅显示匹配的部分和附加的问题(如下面的示例所示),我想排除标题与标题不匹配且部分标题不匹配的问题t匹配。

这是初始数据集:

const sections = 
  [
    {
      title: 'Title section 1',
      questions : [
        {
          title: 'Title question 1'
        },
        {
          title: 'Title question 2'
        }
      ]
     },
    {
      title: 'Title section 2',
      questions : [
        {
          title: 'Title question 3'
        },
        {
          title: 'Title question 4'
        }
      ]
    }
  ]

这是预期的结果:

当针是“第1节”时:

const filteredArray = [  
  {
    title: 'Title section 1',
    questions : [
      {
        title: 'Title question 1'
      },
      {
        title: 'Title question 2'
      }
    ]
  }
]

当针是“问题1”时:

const filteredArray = [  
  {
    title: 'Title section 1',
    questions : [
      {
        title: 'Title question 1'
      }
    ]
  }
]

以此类推。

这是我编写的代码:

const sections = 
  [
    {
      title: 'Title section 1',
      questions : [
        {
          title: 'Title question 1'
        },
        {
          title: 'Title question 2'
        }
      ]
     },
    {
      title: 'Title section 2',
      questions : [
        {
          title: 'Title question 3'
        },
        {
          title: 'Title question 4'
        }
      ]
    }
  ]

const needle = 'question 4'
  
 
const filteredArray = sections.filter(section => section.title.toLowerCase().indexOf(needle.toLowerCase()) !== -1 ||
        section.questions.filter(question => question.title.toLowerCase().indexOf(needle.toLowerCase()) !== -1).length > 0)
        
console.log(filteredArray)

如您所见,经过过滤的结果很好,但是当问题标题和部分标题不匹配时,我无法排除问题。

一个主意?

注意::我使用的是vuejs 2,因此我的原始数组来自商店,为了保持反应性,我不能使用其他数组。

2 个答案:

答案 0 :(得分:0)

我将使用Array.prototype.reduce实现这样的结果:

const needleTitle = 'section 2'
const needleQuestion = 'question 4'

const filteredArray = sections.reduce((acc, section) => {
  // filtering 1-level section list by pushing to acc only needed items
  if (section.title.toLowerCase().indexOf(needleTitle.toLowerCase()) >= 0) {
    // filtering 2-level question list by replacing section.questions with a new list
    const questions = section.questions.filter(question => 
      question.title.toLowerCase().indexOf(needleQuestion.toLowerCase()) >= 0
    )
    acc.push({ ...section, questions });
  }
  return acc;
}, []);

您还看到,我将needle分为needleTitleneedleQuestion。可能这并不是您想要的,但是这个主意应该有用。上面的代码将产生

[  
  {
    title: 'Title section 2',
    questions : [
      {
        title: 'Title question 4'
      }
    ]
  }
]

答案 1 :(得分:0)

感谢@dhilt,这是最终的解决方案:)

ng generate library api