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
相关产品推荐
相关产品推荐

