繁体   English   中英

我认为更好地了解 javascript 数组方法会对我有所帮助吗?

[英]I think a better knowledge of javascript array methods will help me?

我正在尝试在 keystone-next 的自定义突变中更新一系列产品。 我已经做到了以下,这适用于我阵列中的第一个产品。 显然,这仅在数组中只有 1 个项目时才有效。

我知道我需要以某种方式通过阵列 map 但我无法理解它。

const productIds = user.cart.map((cartItem) => cartItem.product.id);
console.log(productIds)
await context.lists.Product.updateMany({
  // this is the bit that's wrong
  data: [
    {
      id: productIds[0],
      data: {
        status: 'PENDING',
      },
    },
  ],
});

是的,您需要通过您的productIds数组 map

const productIds = user.cart.map((cartItem) => cartItem.product.id);

productIds.map(async (id) => {
  await context.lists.Product.updateMany({
    data: [
      {
        id,
        data: {
          status: 'PENDING',
        },
      },
    ],
  });
})

但最有效的是,您应该在第一个map中处理update ,而无需先获取productIds数组。 像这样

user.cart.map(async(cartItem) => {
  await context.lists.Product.updateMany({
    data: [
      {
        id: cartItem.product.id,
        data: {
          status: 'PENDING',
        },
      },
    ],
  });
});

像这样的东西你的意思?

const productIds = user.cart.map((cartItem) => cartItem.product.id);
console.log(productIds)
await context.lists.Product.updateMany({

  data: productIds.map(productId => ({
      id: productId,
      data: {
        status: 'PENDING',
      },
  }))

});

暂无
暂无

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

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