【问题标题】:JavaScript filter should return arrays if the id match如果 id 匹配,JavaScript 过滤器应该返回数组
【发布时间】:2022-01-13 06:38:43
【问题描述】:

我有图书数据。如果书籍与作者的身份证相符,我想退还。当我尝试过滤掉与我的“作者”ID 不匹配的数据时。但是,它总是返回所有图书数据。

const author = "AUTHOR#e9bb9d29-7f20-4fce-892c-6a155dbee42c";

const Book = [
  {
    publishingYear: "2020",
    rating: 5.2,
    GSI1SK: "AUTHOR#a731ea70-f3f3-4811-9734-f22c0856385d",
    genre: ["adventure", "drama", "scifi"],
    GSI1PK: "AUTHOR",
    page: 100,
    publisher: "Afternoon pub",
    SK: "BOOK#c4a58f20-4977-4db8-9723-0185f68cdf01",
    price: "3.50",
    PK: "BOOKS",
    author: "Krishna",
    title: "Me and mySelf"
  },
  {
    publishingYear: "2020",
    rating: 5.2,
    GSI1SK: "AUTHOR#6b7c10ff-0e2c-46bd-9697-3b51730d8b29",
    genre: ["adventure", "drama", "scifi"],
    GSI1PK: "AUTHOR",
    page: 100,
    publisher: "Day pub",
    SK: "BOOK#e4773a32-5451-42c6-a3f1-a6aa45176256",
    price: "3.50",
    PK: "BOOKS",
    author: "John doe",
    title: "Hello world"
  },
  {
    publishingYear: "2020",
    rating: 5.2,
    GSI1SK: "AUTHOR#a731ea70-f3f3-4811-9734-f22c0856385d",
    genre: ["adventure", "drama", "scifi"],
    GSI1PK: "AUTHOR",
    page: 100,
    publisher: "Night Pub",
    SK: "BOOK#fb56a876-41bc-49f9-9762-c48e90af3117",
    price: "3.50",
    PK: "BOOKS",
    author: "Krishna",
    title: "Amazing Race"
  }
];

const Books = Book.filter((i) => {
  console.log(i.GSI1SK);
  i.GSI1SK === author;
  return i;
});

console.log(Books);

【问题讨论】:

  • return i.GSI1SK === author; 不是i。每个对象i 都是真实的。顺便说一句,我不会将i 用于除索引之外的任何内容。首选 e 作为元素或 o 作为对象。

标签: javascript arrays filter


【解决方案1】:

您使用过滤器的方式错误,您应该根据您匹配的条件返回true或false,

const Books = Book.filter((i) => {
  console.log(i.GSI1SK);
  return i.GSI1SK === author;
});

【讨论】:

    【解决方案2】:

    你可以省略不必要的行。试试这个。

    const Books = Book.filter(i => i.GSI1SK === author)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-12
      • 2021-12-29
      • 2022-01-11
      • 2018-08-06
      • 2018-09-29
      • 1970-01-01
      相关资源
      最近更新 更多