对象数组上的过滤器数组包含javascript

时间:2020-01-06 15:12:59

标签: javascript arrays

我有一个像这样的数组:

let posts = [
  {title: "1", tags: ["funny", "good", "nice"]},
  {title: "2", tags: ["weird", "bad"]},
  {title: "3", tags: ["funny", "good"]},
];

我希望数组仅包含“标签”数组具有“有趣”和“好”的对象。数组应包括“标签”数组包含有趣和良好的所有对象。不是只包含“好”和“好”的对象。

这是我现在拥有的,但是它不起作用:

let postsfilter = posts.filter(post => post.tags.indexOf(["funny", "good"]));

4 个答案:

答案 0 :(得分:3)

您可以将.filter().every().includes()一起使用以获取所需的输出:

let posts = [
  {title: "1", tags: ["funny", "good", "nice"]},
  {title: "2", tags: ["weird", "bad"]},
  {title: "3", tags: ["funny", "good"]},
];
let filterBy = ["funny", "good"];

let output = posts.filter(
  ({ tags }) => filterBy.every(s => tags.includes(s))
);

console.log(output);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:2)

您可以使用Array#every获取wanted数组的所有项,并使用Array#includes检查数组是否包含字符串。

let posts = [{ title: "1", tags: ["funny", "good", "nice"] }, { title: "2", tags: ["weird", "bad"] }, { title: "3", tags: ["funny", "good"] }],
    wanted = ["funny", "good"],
    result = posts.filter(({ tags }) => wanted.every(s => tags.includes(s)));
    
console.log(result);

答案 2 :(得分:2)

let postsfilter = posts.filter(post => post.tags.includes("funny") && post.tags.includes("good") );

答案 3 :(得分:1)

let posts = [
  {title: "1", tags: ["funny", "good", "nice"]},
  {title: "2", tags: ["weird", "bad"]},
  {title: "3", tags: ["funny", "good"]},
];

let filtered = posts.filter((v) => v.tags.includes("funny") && v.tags.includes("good"))

console.log(filtered)