Reputation: 91
It is regarding filtering the result. Following code is working fine. But I would like to add one more field. video.description want to add along with 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) {}
};
Upvotes: 3
Views: 288
Reputation: 19070
You can do:
const result = videos.filter(v =>
['title', 'description'].some(prop =>
v[prop].toLowerCase().includes(req.params.word.toLowerCase()))
)
Code example:
// 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)
Upvotes: 1
Reputation: 33
Inside .filter
callback you can't modify a value.
Use forEach
instead. So, you loop through the videos once and you can do with a value whatever you want.
const videos = [ {a:1}, {b:2} ]
const result = []
videos.forEach(value => {
if (value.a) {
value.desription = 'test'
result.push(value)
}
})
result -> [ {a: 1, description: 'test'} ]
Upvotes: 0
Reputation: 27849
First, you do not need to add toString
after toLowerCase
- toLowerCase
is a member function of string
, so you'd get an error for calling it on a value that is not a string (if anything, if you're not sure of the input, do a toSatring().toLowerCase()
).
Second, you can use .includes
to find a substring. No need for indexOf
.
Finally, if you need to add another condition, use the logical AND (&&
) to add the description
condition to the filter function:
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())
);
Upvotes: 0
Reputation: 201
If you want to execute more then just one line of code, you can use the curly brackets.
for example:
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
}
And you don't need toString() after toLowerCase(), because it already returns string
Upvotes: 0