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

JavaScript将含type8/9多选字段的对象数组映射为目标结构数组

JavaScript转换多选类型API返回字段结构

实现思路

  • 遍历输入的属性数组,筛选type值为8或9的多选类型字段
  • 对多选字段,将multiselect_txt和multiselect_id分别按$分隔符拆分为数组,两个数组的索引顺序完全对应
  • 按索引一一映射,生成{name: 选项名, id: 选项ID}格式的选项对象集合
  • 以每个字段的key值作为对象属性名,包装为独立对象后汇总成最终输出数组

完整实现代码

/**
 * 转换接口返回的多选字段为指定结构
 * @param {Array} inputArr 接口返回的原始属性数组
 * @returns {Array} 转换后的目标结构数组
 */
function transformMultiSelect(inputArr) {
  return inputArr.map(item => {
    // 非多选类型直接返回空对象,可按需扩展其他类型的处理逻辑
    if (![8, 9].includes(item.type)) return {};

    // 按$拆分选项文本和选项ID,做空值兼容
    const nameArr = item.multiselect_txt ? item.multiselect_txt.split('$') : [];
    const idArr = item.multiselect_id ? item.multiselect_id.split('$') : [];

    // 按索引映射生成选项列表
    const optionList = nameArr.map((name, idx) => ({
      name,
      id: Number(idArr[idx])
    }));

    return {
      [item.key]: optionList
    };
  });
}

// 测试用例
const rawData = [
  {
    key: 'attribute1',
    type: 8,
    multiselect_txt: 'Apple$Carrot$Plum',
    multiselect_id: '34$13$21'
  },
  {
    key: 'attribute2',
    type: 8,
    multiselect_txt: 'Coke$Juice',
    multiselect_id: '11$26'
  }
];

const result = transformMultiSelect(rawData);
console.log(result);

注意事项

  • 代码做了空值兼容处理,若多选字段没有选中值(即multiselect_txt/multiselect_id为空),不会抛出运行时错误
  • 输出的选项id默认转为数字类型,如果业务需要保留字符串格式,去掉外层的Number()转换即可
  • 非8/9类型的字段当前默认返回空对象,可根据实际业务需求补充其他字段类型的转换逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 08:36:27