The structure of the objects inside the array to filter is the following:
videos:[
{
name: 'video name'
url: 'video url'
tags: [
{
tag: 'reels',
// other tag info
},
{
tag: 'demos',
// other tag info
},
]
},
...
]
i need to filter the videos array by the property tag on the objects inside the tags array, for example, i need to get an array with all the video objects on which tags array exist an object with the tag property 'reels'
what i tried*
videos.filter(video => video.tags.tag === 'reels');
that returns an empty array because i'm not accessing the objects inside tags to read the tag property, so i tried the following
videos.filter(video => {
video.tags.forEach(tag => {
if (tag.tag === 'reels') {
return true:
};
});
});
that looks kinda crazy and inconsistent, but i thought that i could iterate over the tags array inside each video being iterated on the videos.filter and return true, but it doesnt work
有几种方法可以完成同样的事情,可以用.some
来做到这一点,它“测试数组中是否至少有一个元素通过了由提供的函数实现的测试。 ”
videos.filter(video => video.tags.some(t => t.tag === "reels"));
You were very close to correct with the second try. If you change it from forEach to find and return the value, it will work.
const videos = [ { name: 'video name', url: 'video url', tags: [ { tag: 'reels', }, { tag: 'demos', }, ] }, { name: 'video name2', url: 'video url2', tags: [ { tag: 'demos', }, ] }, ]; const filtered = videos.filter(video => { return video.tags.find(tag => { if (tag.tag === 'reels') { return true; }; }); }); console.log(filtered); // shortened to one line const filtered2 = videos.filter(video => video.tags.find(tag => tag.tag === 'reels')); console.log(filtered2);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.