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

JavaScript嵌套JSON与数组处理面试题:实现通用商品轮播数据映射函数

解决方案

核心思路

我们的核心是把所有数据结构差异收敛到配置层,处理逻辑完全通用,不需要针对不同API做修改:

  • 配置中声明从输入payload提取商品数组的路径
  • 配置中声明每个输出字段对应商品对象的读取路径、输出类型,可选择性增加自定义转换函数处理特殊格式
  • 实现通用的嵌套属性读取工具,支持任意层级的对象、数组属性读取

完整实现代码

// 通用嵌套属性读取工具:传入对象和点分隔的路径,返回对应属性值
const getNestedValue = (target, path) => {
  return path.split('.').reduce((res, key) => res?.[key], target);
};

/**
 * 通用数据处理函数
 * @param {Object} payload 接口返回的原始数据
 * @param {Object} config 适配配置
 * @param {String} config.listPath 从payload中提取商品数组的路径
 * @param {Array} config.fields 输出字段配置,每个元素包含:
 *   - type: 输出字段类型
 *   - getPath: 从单个商品对象读取值的路径
 *   - transform: [可选] 对读取到的值做自定义转换的函数
 * @returns {Array} 适配完成的嵌套数组
 */
const processData = (payload, config) => {
  // 第一步:提取商品数组
  const productList = getNestedValue(payload, config.listPath);
  // 第二步:遍历每个商品做字段映射
  return productList.map(product => {
    return config.fields.map(field => {
      const rawValue = getNestedValue(product, field.getPath);
      const finalValue = field.transform ? field.transform(rawValue) : rawValue;
      return {
        type: field.type,
        value: finalValue
      };
    });
  });
};

使用示例

适配示例1的配置

const configForDemo1 = {
  listPath: 'payload.0.data',
  fields: [
    { type: 'TEXT', getPath: '0.name' },
    { type: 'URL', getPath: '0.url' },
    { type: 'IMAGE', getPath: '0.images.medium' },
    { type: 'TEXT', getPath: '0.price' }
  ]
};
// 调用:processData(demo1Payload, configForDemo1) 即可得到预期输出

适配示例2的配置

const configForDemo2 = {
  listPath: '0',
  fields: [
    { type: 'TEXT', getPath: 'meta.en_US.product_name' },
    { type: 'URL', getPath: 'meta.en_US.product_urls.0' },
    { type: 'IMAGE', getPath: 'meta.en_US.product_image_medium' },
    { type: 'TEXT', getPath: 'meta.en_US.product_custom_attributes.product_price_string' }
  ]
};
// 调用:processData(demo2Payload, configForDemo2) 即可得到和示例1完全一致的输出

如果遇到需要特殊转换的场景,比如价格需要从分转为美元格式,直接在字段配置里加transform即可:

{
  type: 'TEXT',
  getPath: 'meta.en_US.product_price_cents',
  transform: (cents) => `$${(cents / 100).toFixed(2)}`
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 13:24:09