它是关于过滤结果。下面的代码运行良好。但我想再加一个字段。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) {}
};发布于 2020-03-10 06:39:47
你可以:
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)
发布于 2020-03-10 06:12:07
如果您想执行更多的代码,那么只需执行一行代码,就可以使用花括号。
例如:
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(),因为它已经返回了字符串
发布于 2020-03-10 06:14:11
首先,您不需要在toString之后添加toLowerCase - toLowerCase是string的一个成员函数,因此如果对一个不是字符串的值调用它时会出现一个错误(如果有的话,如果您不确定输入,那么执行一个toSatring().toLowerCase())。
其次,可以使用.includes查找子字符串。不需要indexOf。
最后,如果需要添加另一个条件,请使用逻辑和(&&)将description条件添加到筛选器函数中:
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())
);https://stackoverflow.com/questions/60612287
复制相似问题