【发布时间】:2021-10-02 06:28:31
【问题描述】:
我正在尝试获取 favorite.user Id 和用户。 id 要匹配,这样我就可以将单个用户的产品添加到他们的最爱中,这是我尝试过的。
const product = [
{
name: "Product A",
price: "$100",
favorites: [
{
_id: "60fe705efc8be22860620d3b",
userId: "3",
username: "Alif",
createdAt: "2021-07-26T08:20:46.522Z",
},
],
},
{
name: "Product B",
price: "$300",
favorites: [
{
_id: "60fe705efc8be22860620d3b",
userId: "1",
username: "John",
createdAt: "2021-07-26T08:20:46.522Z",
},
],
},
{
name: "Product C",
price: "$1300",
favorites: [
{
_id: "60fe705efc8be22860620d3b",
userId: "1",
username: "John",
createdAt: "2021-07-26T08:20:46.522Z",
},
],
},
];
const user = {
id: "1",
};
const favoriteUser = product?.map(({ favorites }) => {
return favorites.map(({ userId }) => {
return userId;
});
});
const wishlistProduct = product?.filter(() => {
return user.id === favoriteUser;
});
console.log(wishlistProduct);
例如,我希望它返回对象产品 B 和产品 C,因为它们共享相同的 id。 user.id 和 favorite.userId 是相同的。如果您有不明白的地方,请告诉我,我会尽力向您解释。
【问题讨论】:
标签: javascript arrays json object filter