You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将自有商品数组转换为pro-gallery库要求的图片对象数组格式

商品数组转pro-gallery要求格式实现方案

字段映射关系

  • itemId 取原商品数组的 _id 字段
  • mediaUrl 取原商品数组的 image 字段
  • metaData.title 取原商品数组的 name 字段
  • metaData.description 取原商品数组的 description 字段
  • metaData.type 固定写为 image
  • 原数组无图片宽高字段,可根据需求选择填默认值或预加载图片获取真实宽高

基础同步实现(使用默认宽高)

如果对图片展示精度要求不高,直接使用默认宽高即可,pro-gallery会自动适配图片比例:

// 假设原商品数据存储在products变量中
const galleryItems = products.map(product => ({
  itemId: product._id,
  mediaUrl: product.image,
  metaData: {
    type: "image",
    width: 100,
    height: 100,
    title: product.name,
    description: product.description
  }
}))

异步实现(获取真实图片宽高)

如果需要传入图片真实宽高,可通过预加载图片的方式获取:

const generateGalleryItems = async (products) => {
  const result = []
  for (const product of products) {
    const img = new Image()
    img.src = product.image
    // 等待图片加载完成获取宽高
    await new Promise((resolve) => {
      const pushItem = (width = 100, height = 100) => {
        result.push({
          itemId: product._id,
          mediaUrl: product.image,
          metaData: {
            type: "image",
            width,
            height,
            title: product.name,
            description: product.description
          }
        })
        resolve()
      }
      img.onload = () => pushItem(img.naturalWidth, img.naturalHeight)
      img.onerror = () => pushItem() // 加载失败用默认值
    })
  }
  return result
}

// 调用方式
const galleryItems = await generateGalleryItems(products)

内容的提问来源于stack exchange,提问作者Guillaume Ayad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 23:06:03