简体   繁体   English

过滤数组后返回对象值

[英]Return Object value after Filtering an Array

I'm trying to get the favorite.user Id and the user.我正在尝试获取最喜爱的用户 ID 和用户。 id to match so I could get the product of the individual user added to their favorite here is what I have tried. 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);

I intended it to return both the object Product B and Product C, for example, because they share the same ids.例如,我希望它同时返回对象 Product B 和 Product C,因为它们共享相同的 ID。 The user.id and the favorite.userId are identical. user.id 和 favorite.userId 是相同的。 If you don't understand something, please let me know and I'll try to explain it to you.如果您有什么不明白的地方,请告诉我,我会尽力向您解释。

Just use filter with proper predicate只需使用带有适当谓词的过滤器

product.filter(({ favorites }) => favorites.some(({ userId }) => userId === user.id))

 const product = JSON.parse(`[{\\"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 result = product.filter(({ favorites }) => favorites.some(({ userId }) => userId === user.id)) console.log(result)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM