使用过滤器以array作为值查询json



我有以下json数据与videos数组,其中几个声明设置在里面。可以看到,有一个参数categoryteam的值与另一个数组的参与者的名字。

{
"videos" : [
{
"url" : "https://www.youtube.com/watch?v=5678",
"category" : "Enterview",
"team" : ["Prince Kyle","Rod Patrón"]
},
{
"url" : "https://www.youtube.com/watch?v=1234",
"category" : "Post-Game",
"team" : ["Rod Patrón","Tony Backy","Prince Kyle"]
},
{
"url" : "https://www.youtube.com/watch?v=0186",
"category" : "Post-Game",
"team" : ["Risto Stoichkov"]
}
]
}

我想循环根据类别和团队的组合(其中包含多个值)。

我尝试了下面的代码,在这里我只想查询与Risto和Tony的赛后视频:

var filterList = data.videos
.filter(({ category }) => category === "Post-Game")
.filter(({ team }) => team === ["Risto Stoichkov", "Tony Backy"])

它适用于类别,但是,我不能循环名称。可以看出,我的意图是在必要时应用多个名称。

我相信你的目标如下。

  • 您想要过滤问题中的值。
  • 您希望使用categoryteam的值作为过滤值。
  • 你想用Javascript实现这个。

修改点:

  • 在您的脚本中,在.filter(({ team }) => team === ["Risto Stoichkov", "Tony Backy"]),team是一个数组。在这种情况下,数组被比较。

模式1:

修改后的脚本如下所示:

const data = {
"videos": [
{
"url": "https://www.youtube.com/watch?v=5678",
"category": "Enterview",
"team": ["Prince Kyle", "Rod Patrón"]
},
{
"url": "https://www.youtube.com/watch?v=1234",
"category": "Post-Game",
"team": ["Rod Patrón", "Tony Backy", "Prince Kyle"]
},
{
"url": "https://www.youtube.com/watch?v=0186",
"category": "Post-Game",
"team": ["Risto Stoichkov"]
}
]
};
var filterList = data.videos
.filter(({ category }) => category === "Post-Game")
.filter(({ team }) => ["Risto Stoichkov", "Tony Backy"].some(e => team.includes(e)));
console.log(filterList)

模式2:

我认为在这种情况下,您的目标可能会实现使用一个filter。示例脚本如下:

const data = {
"videos": [
{
"url": "https://www.youtube.com/watch?v=5678",
"category": "Enterview",
"team": ["Prince Kyle", "Rod Patrón"]
},
{
"url": "https://www.youtube.com/watch?v=1234",
"category": "Post-Game",
"team": ["Rod Patrón", "Tony Backy", "Prince Kyle"]
},
{
"url": "https://www.youtube.com/watch?v=0186",
"category": "Post-Game",
"team": ["Risto Stoichkov"]
}
]
};
var filterList = data.videos
.filter(({ category, team }) => category === "Post-Game" && ["Risto Stoichkov", "Tony Backy"].some(e => team.includes(e)));
console.log(filterList)

模式3:

我认为当一个对象准备好搜索值时,过程成本可能会降低。示例脚本如下:

const data = {
"videos": [
{
"url": "https://www.youtube.com/watch?v=5678",
"category": "Enterview",
"team": ["Prince Kyle", "Rod Patrón"]
},
{
"url": "https://www.youtube.com/watch?v=1234",
"category": "Post-Game",
"team": ["Rod Patrón", "Tony Backy", "Prince Kyle"]
},
{
"url": "https://www.youtube.com/watch?v=0186",
"category": "Post-Game",
"team": ["Risto Stoichkov"]
}
]
};
var names = ["Risto Stoichkov", "Tony Backy"];
var obj = names.reduce((o, e) => ({...o, [e]: true}), {});
var filterList = data.videos
.filter(({ category, team }) => category === "Post-Game" && team.some(e => obj[e]));
console.log(filterList)

引用:

  • 过滤器()
  • 一些()

相关内容

  • 没有找到相关文章

最新更新