在带有对象的嵌套数组中过滤

时间:2020-09-19 23:22:35

标签: javascript filter

我有一个包含三个书本对象的数组。每个book对象都有一个bookIds数组。我想以快速有效的方式按bookId(3,1)进行过滤,因为我的数组将来会很容易地长大。我尝试使用map,但是即使使用deepCopy,它也会更改我的原始数组!有没有一种方法可以使用过滤器功能而不使用递归?

this.booksList = 
    [
      {
        "books": [
          {
            "bookId": 3
          },
          {
            "bookId": 2
          }
        ],
        "id": 1,
        "name": "Name 1",
        "description": "desc 1"
      },
      {
        "books": [
          {
            "bookId": 5
          },
          {
            "bookId": 2
          }
         ],
         "id": 2,
         "name": "Name 2",
         "description": "desc 2"
      },
      {
        "books": [
          {
            "bookId": 1
          },
          {
            "bookId": 3
          }
         ],
         "id": 3,
         "name": "Name 3",
         "description": "desc 3"
      }
    ]

地图方法:

let results = this.books.map(function (book) {
            book.books = book.books.filter(x => x.bookId == 1 || x.bookId == 3);
            return book;
        }).filter(({ books }) => books.length);

带地图的结果:未达到预期的结果!

[
  {
    "books": [
      {
        "bookId": 3
      }
    ],
    "id": 1,
    "name": "Name 1",
    "description": "desc 1"
  },
  {
    "books": [
      {
        "bookId": 1
      },
      {
        "bookId": 3
      }
     ],
     "id": 3,
     "name": "Name 3",
     "description": "desc 3"
  }
]

预期结果:

[
  {
    "books": [
      {
        "bookId": 3
      },
      {
        "bookId": 2
      }
    ],
    "id": 1,
    "name": "Name 1",
    "description": "desc 1"
  },
  {
    "books": [
      {
        "bookId": 1
      },
      {
        "bookId": 3
      }
     ],
     "id": 3,
     "name": "Name 3",
     "description": "desc 3"
  }
]

谢谢

2 个答案:

答案 0 :(得分:2)

我认为您正在寻找filtersome-

const input =
  [{books:[{bookId:3},{bookId:2}],id:1,name:"Name 1",description:"desc 1"},{books:[{bookId:5},{bookId:2}],id:2,name:"Name 2",description:"desc 2"},{books:[{bookId:1},{bookId:3}],id:3,name:"Name 3",description:"desc 3"}]

const query =
  [3, 1]

const result =
  input.filter(({ books = [] }) =>
    books.some(({ bookId = null }) => query.includes(bookId))
  )

console.log(JSON.stringify(result, null, 2))

输出-

[
  {
    "books": [
      {
        "bookId": 3
      },
      {
        "bookId": 2
      }
    ],
    "id": 1,
    "name": "Name 1",
    "description": "desc 1"
  },
  {
    "books": [
      {
        "bookId": 1
      },
      {
        "bookId": 3
      }
    ],
    "id": 3,
    "name": "Name 3",
    "description": "desc 3"
  }
]

答案 1 :(得分:0)

const booksList=[
  {books:[{bookId:3},{bookId:2}],id:1,name:"Name 1",description:"desc 1"},
  {books:[{bookId:5},{bookId:2}],id:2,name:"Name 2",description:"desc 2"},
  {books:[{bookId:1},{bookId:3}],id:3,name:"Name 3",description:"desc 3"},
];

const byBookIDs = (...IDs) =>
  booksList.filter(b => b.books.some(b => IDs.includes(b.bookId)));

console.log(byBookIDs(1, 3));