首页 > 解决方案 > 过滤结果

问题描述

它是关于过滤结果的。以下代码工作正常。但我想再添加一个字段。video.description 要与 video.title 一起添加

      exports.getSearchvideo = async (req, res) => {
      try {
        const videos = await Video.find();
        const index = videos.filter(
          video =>
            video.title
              .toLowerCase()
              .toString()
              .indexOf(req.params.word.toLowerCase().toString()) > -1
// want to add video.description
        );
        res.send(index);
      } catch (error) {}
    };

标签: javascriptnode.jsreactjs

解决方案


你可以做:

const result = videos.filter(v => 
  ['title', 'description'].some(prop =>
    v[prop].toLowerCase().includes(req.params.word.toLowerCase()))
)

代码示例:

// API videos response
const videos = [{ title: 'Title for Video 1', description: 'Description', }, { title: 'Title for Video 2', description: 'Some description here' }]
const word = 'VIDEO 1'

const result = videos.filter(v =>
  ['title', 'description'].some(prop => v[prop].toLowerCase().includes(word.toLocaleLowerCase()))
)

console.log(result)


推荐阅读