首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >过滤结果

过滤结果
EN

Stack Overflow用户
提问于 2020-03-10 06:05:11
回答 4查看 198关注 0票数 3

它是关于过滤结果。下面的代码运行良好。但我想再加一个字段。video.description希望与video.title一起添加

代码语言:javascript
运行
复制
      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) {}
    };
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2020-03-10 06:39:47

你可以:

代码语言:javascript
运行
复制
const result = videos.filter(v => 
  ['title', 'description'].some(prop =>
    v[prop].toLowerCase().includes(req.params.word.toLowerCase()))
)

代码示例:

代码语言:javascript
运行
复制
// 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)

票数 1
EN

Stack Overflow用户

发布于 2020-03-10 06:12:07

如果您想执行更多的代码,那么只需执行一行代码,就可以使用花括号。

例如:

代码语言:javascript
运行
复制
video => { 
    const titleResult = video.title.toLowerCase().indexOf(req.params.word.toLowerCase()) > -1 
    const descriptionResult = video.description.toLowerCase().indexOf(req.params.word.toLowerCase()) > -1 
    return result1 && result2 
} 

而且您不需要在toString()之后使用toLowerCase(),因为它已经返回了字符串

票数 0
EN

Stack Overflow用户

发布于 2020-03-10 06:14:11

首先,您不需要在toString之后添加toLowerCase - toLowerCasestring的一个成员函数,因此如果对一个不是字符串的值调用它时会出现一个错误(如果有的话,如果您不确定输入,那么执行一个toSatring().toLowerCase())。

其次,可以使用.includes查找子字符串。不需要indexOf

最后,如果需要添加另一个条件,请使用逻辑和(&&)将description条件添加到筛选器函数中:

代码语言:javascript
运行
复制
const index = videos.filter(
    video =>
        video.title.toString().toLowerCase()
            .includes(req.params.word.toString().toLowerCase())
        && video.description.toString().toLowerCase()
            .includes(req.params.anotherWord.toString().toLowerCase())
);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60612287

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档