【问题标题】:How to filter an array in array of objects in Javascript?如何在Javascript中过滤对象数组中的数组?
【发布时间】:2021-09-07 16:42:19
【问题描述】:
 const books = [{
     id: "1",
     title: "Book title",
     areas: ["horror", "mystery"]
   }, {
     id: "2",
     title: "Book title 2",
     areas: ["friendship", "love", "history"]
   },
   {
     id: "2",
     title: "Book title 3",
     areas: ["friendship", "scifi"]
   }
 ];

这是我的书籍阵列,我想根据区域制作一个新阵列。例如,如果用户单击按钮 - 恐怖,那么我只想加载在他们的 -areas- 中有恐怖的书籍, 我是 JS 的新手,我找不到正确的方法。 我想创建一个名为filteredBooks 的新数组。感谢您的帮助!

【问题讨论】:

  • 使用Array.includes() 方法。
  • @Mike'Pomax'Kamermans 我不认为这是一个很好的复制品。它不是在嵌套数组中搜索值。
  • 我确定有重复的,但我现在找不到。
  • @barmar 问题标题具有误导性,实际问题本身与“带有对象的数组”相同。不是真正的嵌套数组。
  • 都是对象数组,但是属性的比较方法完全不同。

标签: javascript


【解决方案1】:

filter() -> 使用回调函数,其返回值决定过滤后的数组中返回的内容。如果返回值为 true,则该项目包含在结果数组中。

includes() -> 使用 == 相等性在项目数组中搜索某些内容

const books = [{
     id: "1",
     title: "Book title",
     areas: ["horror", "mystery"]
   }, {
     id: "2",
     title: "Book title 2",
     areas: ["friendship", "love", "history"]
   },
   {
     id: "2",
     title: "Book title 3",
     areas: ["friendship", "scifi"]
   }
];

const filterValue = "horror";
const filteredBooks = books.filter(val => val.areas.includes(filterValue));
console.log(filteredBooks);

【讨论】:

    【解决方案2】:

    由于已经有一个很好的答案(@Kirill Savik)来查找单一类型的书,我将借此机会扩展给定的答案,以便它可以包含一系列类型显示至少包含其中一种类型的书籍。

    看看这个sn-p:

    const books = [
        {
            id: "1",
            title: "Book title",
            areas: ["horror", "mystery"]
        }, 
        {
            id: "2",
            title: "Book title 2",
            areas: ["friendship", "love", "history"]
        },
        {
            id: "2",
            title: "Book title 3",
            areas: ["friendship", "scifi"]
        }
    ];
    
    function filter_books(filters) {
        const filteredBooks = [];
        filters.forEach(filterValue => {
            filteredBooks.push(...books.filter(val => val.areas.includes(filterValue)));
        });
        console.log(filteredBooks);
    };
    
    filter_books(["horror", "scifi"]); // Outputs all books which have one or more of these ^ genres

    【讨论】:

    • 对书籍进行过滤会更容易一些,使用some检查areas是否包含过滤器:return books.filter(val => filters.some(filter => val.areas.includes(filter)))
    猜你喜欢
    • 2021-04-23
    • 2018-11-22
    • 2020-07-03
    • 2022-10-14
    • 2016-10-12
    • 2020-08-09
    • 1970-01-01
    • 2020-07-11
    相关资源
    最近更新 更多