如何使用逗号分隔的元素成为对象 [英] How to make object of comma separated elements
问题描述
我正在使用CSV解析器,其中的数据在数组中,如
I am working on a CSV parser, where I have data in array like
["Jonas", "Sched ", "jonas@sch.com", "ph:34988934", "data 1,data 2", "data 3,data 4", "data 5, data 6"]
我要实现的目标是制作包含逗号(,
)的array元素的对象数组.
What I want to achieve I want to make array of object of array element which contain comma (,
).
预期结果:
let array= ["Jonas", "Sched ", "jonas@sch.com", "ph:34988934", items:[{name:data 1, temp:data
2},{name:data 3, temp:data 4},{name:data 5, temp:data 6}]
推荐答案
您的第一步是从原始数组中提取内容.这可以通过解构分配来完成.:
Your first step is to pull things out of your original array. This can be done through a destructuring assignment:
const [name, company, email, phone, ...itemCsvs] = yourOriginalArray;
注意 ... itemCsvs
;将前四个项目之后剩余的所有内容分解为变量名称为 itemCsvs
的数组.
Notice the ...itemCsvs
; that destructures anything remaining after the first four items into an array with the variable name itemCsvs
.
itemCsvs
中的每个项目看起来都以逗号分隔.您可以使用 split 这些字符串的code>方法
将它们转换为字符串数组:
Each item in itemCsvs
looks like comma-separated pairs. You can use the split
method of those strings to convert them to string arrays:
const itemPairs = itemCsvs.map(str => str.split(','));
itemPairs
现在是字符串数组的数组.
itemPairs
is now an array of string arrays.
[
["data1", "data2"],
["data3", "data4"],
["data5", "data6"]
]
然后将它们转换为对象就像再次映射一样简单:
Converting these into objects is then as simple as mapping again:
const items = itemPairs.map(([name, temp]) => ({ name, temp }));
现在,您只需重新组装各个部分即可.为了更紧凑地组合在一起:
Now you just reassemble the pieces. To put things together more compactly:
const originalData = [
"Jonas", "Sched ", "jonas@sch.com", "ph:34988934",
"data 1,data 2", "data 3,data 4", "data 5, data 6"
];
const [name, company, email, phone, ...itemCsvs] = originalData;
const result = {
name, company, email, phone,
items: itemCsvs.map(item => {
const [name, temp] = item.split(',');
return { name, temp };
})
};
console.log(result);
这篇关于如何使用逗号分隔的元素成为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!