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

JS按前缀匹配合并对象属性值并按配置添加分隔符的实现问题

解决方案

完整代码

const lookup = [
  {prefix: "fruit", key: "sweet", "separator": "###" }, 
  {prefix: "rate" }, // 无分隔符和key配置时默认将prefix作为输出属性名
];

const input = [{
  fruit_a: "red apple",
  fruit_b: "green apple",
  rate_a: "10$",
  rate_b: "20$",
  vegetable_a: "spinach",
  vegetable_b: "carrot",
},
{
  fruit_d: "white apple",
  fruit_e: "yellow apple",
  rate_d: "10$",
  rate_e: "20$",
  vegetable_d: "radish",
  vegetable_e: "cabbage",
}
];

const result = input.map(currentObj => {
  return Object.entries(currentObj).reduce((acc, [key, value]) => {
    // 查找匹配的前缀规则
    const matchedRule = lookup.find(rule => key.startsWith(rule.prefix));
    if (!matchedRule) {
      // 未匹配规则的属性直接保留
      return {...acc, [key]: value};
    }
    // 补全规则默认值:无key用prefix,无分隔符用逗号
    const targetKey = matchedRule.key ?? matchedRule.prefix;
    const separator = matchedRule.separator ?? ',';
    // 拼接值
    acc[targetKey] = acc[targetKey] ? `${acc[targetKey]}${separator}${value}` : value;
    return acc;
  }, {});
});

console.log(result);

核心修改说明

  • 原代码错误地直接对数组类型的input执行Object.entries处理,导致多个输入对象的属性被合并到同一个结果中,现在改为先通过map遍历input的每个对象,单独处理后返回结果数组,符合预期结构。
  • 补全了lookup规则的默认值逻辑:未配置key时自动用prefix作为输出属性名,未配置separator时默认使用逗号作为分隔符。
  • 不再将匹配到的属性值存入数组,处理过程中直接按对应分隔符拼接为字符串,省去二次转换步骤。
  • 修正了原代码中规则匹配后的属性名取值错误问题,避免生成不存在的属性名。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 06:15:01