过滤数组后返回对象值

时间:2021-07-26 09:51:51

标签: javascript arrays json object filter

我正在尝试获取最喜爱的用户 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);

例如,我希望它同时返回对象 Product B 和 Product C,因为它们共享相同的 ID。 user.id 和 favorite.userId 是相同的。如果您有不明白的地方,请告诉我,我会尽力向您解释。

1 个答案:

答案 0 :(得分:2)

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

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)

相关问题