【问题标题】:Return Object value after Filtering an Array过滤数组后返回对象值
【发布时间】: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


    【解决方案1】:

    只需使用带有适当谓词的过滤器

    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)

    【讨论】:

    • 很高兴我能帮上忙 :)
    猜你喜欢
    • 1970-01-01
    • 2017-10-07
    • 1970-01-01
    • 2019-01-22
    • 1970-01-01
    • 1970-01-01
    • 2020-12-13
    • 1970-01-01
    相关资源
    最近更新 更多