简体   繁体   English

Javascript 如何按参数过滤数组

[英]Javascript How to Filter Array By Parameter

I have an array of JSON objects ("posts") in which each object contains an array of tags (strings).我有一个 JSON 对象(“帖子”)数组,其中每个 object 包含一个标签数组(字符串)。 I want to filter the posts by passing in a tag.我想通过传入标签来过滤帖子。 Such that for example, if I have 10 posts and 2 of them are tagged as "news" then I return the 2 post objects with that tag.例如,如果我有 10 个帖子,其中 2 个被标记为“新闻”,那么我返回带有该标签的 2 个帖子对象。

Here's what I've tried:这是我尝试过的:

const filteredData = posts.filter(((post, tag) =>
      post.tags.filter((t, tag) => t == tag)
    ));

The above code does not work;上面的代码不起作用; it acts like every post is valid when that's not true.当这不是真的时,它就像每个帖子都是有效的。 My guess is that each "tag" is a new variable and does not get passed down properly, since that's what VS Code seems to indicate from the color highlighting.我的猜测是每个“标签”都是一个新变量,并且没有正确传递,因为这似乎是 VS Code 从颜色突出显示中所表明的。

I cannot figure out the proper syntax for this problem.我无法弄清楚这个问题的正确语法。 I am sure this is super simple though.我相信这非常简单。

This site explains how the filter method works, but it doesn't explain how to pass in a parameter.该站点解释了过滤器方法的工作原理,但没有解释如何传入参数。 It shows an example with a hard-coded number.它显示了一个带有硬编码数字的示例。 In my case, I need to pass in the tag parameter so that I can check against a given tag.就我而言,我需要传入标签参数,以便我可以检查给定的标签。

Every other question related to this on Stack Overflow I've found is way more complicated than what I'm trying to do and does not clearly explain how the syntax works.我发现在 Stack Overflow 上与此相关的所有其他问题都比我尝试做的要复杂得多,并且没有清楚地解释语法是如何工作的。 Any help is appreciated.任何帮助表示赞赏。

You can access outside variables from within the function.您可以从 function 中访问外部变量。

const tagToFilter = "..."

const filteredData = posts.filter((post) =>
  post.tags.includes(tagToFilter)
);

Note that I switched the inside function to use .includes() .请注意,我将内部 function 切换为使用.includes() If you needed to use a function for that, you should use .some() instead of .filter() (for the inside function).如果您需要为此使用 function,则应使用.some()而不是.filter() (用于内部函数)。

filter need a return boolean, but u just return a new array, u can use.some() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some过滤器需要返回 boolean,但你只返回一个新数组,你可以使用.some() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some

it should be like this应该是这样的

const filteredData = posts.filter(((post, tag) =>
  post.tags.some((t, tag) => t === tag)
));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM