开发者问题收集

JavaScript:通过另一个对象过滤对象数组

2022-02-26
69

我尝试根据另一个对象数组过滤一些对象。因此,我从 API 获取数据。例如,这些是收据:

[
  {
    "id": 1,
    "name": "test",
    "category": {
        "id": 1,
        "name": "Cookies",
    },
  },
  {
    "id": 2,
    "name": "test2",
    "category": {
        "id": 2,
        "name": "Candy",
    },
  }
]

然后,我尝试根据另一个类别数组按类别名称过滤对象。 我为此创建了一个函数:

function onSelectCategory(category) {
  let receiptsList = receipts.filter((a) =>
    a.category.includes(category.name)
  );
  setReceiptsView(receiptsList);
  setSelectedCategory(category);
}

const category = [ { "id": 2, "name": "Candy" } ];
onSelectCategory(category);

当我运行此函数时,我得到一个空数组 [] 。我真的不知道我做错了什么。

2个回答

由于 param 似乎是一个对象数组,因此您需要使用 Array#some 进行比较:

const receipts = [
  { "id": 1, "name": "test", "category": { "id": 1,  "name": "Cookies" } },
  { "id": 2, "name": "test2", "category": { "id": 2, "name": "Candy" } }
];
const categories = [ { "id": 2, "name": "Candy" } ];

const receiptsList = receipts.filter(({ category }) => 
  categories.some(({ name }) => name === category.name)
);

console.log(receiptsList);

另一种解决方案是使用 Set

const receipts = [
  { "id": 1, "name": "test", "category": { "id": 1,  "name": "Cookies" } },
  { "id": 2, "name": "test2", "category": { "id": 2, "name": "Candy" } }
];
const categories = [ { "id": 2, "name": "Candy" } ];

const categorySet = new Set(categories.map(({ name }) => name));

const receiptsList = receipts.filter(({ category }) => 
  categorySet.has(category.name)
);

console.log(receiptsList);
Majed Badawi
2022-02-26

假设 category (参数)是一个字符串,问题在于您试图从字符串中获取属性 name ,而您应该将字符串与对象进行比较。

试试这个:

a.category.name == category;

而不是

a.category.includes(category.name)

我可能错误地假设 category 是一个字符串,请告诉我们参数 category 等于什么。

s2_6348576
2022-02-26