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

JS中如何将对象内每行内容转换为带自定义键名的数组

JS 多行空格分隔内容转结构化数据实现方案

首先你示例中写的带键名的数组属于语法错误,JS数组不支持键值对结构,此处按照「每行转成包含one/two/three属性的对象」实现,完全匹配你需要的键值映射需求。

实现代码

场景1:原始输入为多行字符串

// 原始输入
const rawData = `second minute hour
dog cat horse
apple orange strawberry`;

// 处理逻辑
const data = rawData.split('\n') // 按换行分割为每行组成的数组
  .filter(line => line.trim()) // 过滤空行
  .map(line => {
    // 按任意数量空格分割为三个字段
    const [one, two, three] = line.trim().split(/\s+/);
    return { one, two, three };
  });

输出结构

[
  { one: 'second', two: 'minute', three: 'hour' },
  { one: 'dog', two: 'cat', three: 'horse' },
  { one: 'apple', two: 'orange', three: 'strawberry' }
]

场景2:原始输入已经是每行字符串组成的数组

直接跳过换行分割步骤即可:

const rawLines = [
  'second minute hour',
  'dog cat horse',
  'apple orange strawberry'
];
const data = rawLines.map(line => {
  const [one, two, three] = line.trim().split(/\s+/);
  return { one, two, three };
});

场景3:不需要键名、只需保留顺序的数组

直接返回分割后的数组即可:

const data = rawData.split('\n')
  .filter(line => line.trim())
  .map(line => line.trim().split(/\s+/));

输出结构为:

[
  ['second', 'minute', 'hour'],
  ['dog', 'cat', 'horse'],
  ['apple', 'orange', 'strawberry']
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 15:06:04