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

如何使用数组方法将逗号分隔字符串转为数组格式JSON

解决方案:将对象中逗号分隔的字符串值转为数组

你可以通过组合使用Object.entries()、Array.prototype.map()和String.prototype.split()这几个方法来实现需求,完全符合你想用数组方法的思路:

代码实现

// 原始输入对象
const input = {
    name1:"john,doe",
    name2:"peter,frank"
};

// 转换逻辑
const output = Object.fromEntries(
  Object.entries(input).map(([key, value]) => [
    key,
    value.split(',')
  ])
);

console.log(output);

执行结果

{
  name1: ["john", "doe"],
  name2: ["peter", "frank"]
}

步骤说明

  • Object.entries(input):把原始对象转换为键值对组成的数组,结构为[['name1', 'john,doe'], ['name2', 'peter,frank']]
  • .map(([key, value]) => ...):遍历键值对数组,对每一项进行转换处理
  • value.split(','):将逗号分隔的字符串拆分为子字符串数组,比如'john,doe'会被转为['john', 'doe']
  • Object.fromEntries(...):将处理后的键值对数组重新转换为对象结构

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 03:01:07