我正在尝试将CSV字符串转换为对象数组的数组。尽管问题是,在传入请求的主体中有一堆n
,它们导致请求分裂并弄乱所有代码。我试图解决这个问题,即使在正文中有n
字符串看起来像这样,所有的消息都是来自传入请求的字符串,从"
开始,以"
结束。
"id,urn,title,body,risk,s.0.id,s.1.id,s.2.id,a.0.id,a.1.id,a.2.id,a.3.id
302,25,"Secure Data","Banking can save a lot of time but it’s not without risks. Scammers treat your bank account as a golden target –
it can be a quick and untraceable way to get money from younn**TOP TIPS**nn**Always read your banks rules.** These tips don’t replace your banks rules -
in fact we fully support them. If you don’t follow their rules, you may not get your money back if you are defrauded nn**Saving passwords or allowing auto-complete.**
Saving passwords in your browser is great for remembering them but if a hacker is able to access your computer, they will also have access to your passwords.
When on your banking site the password box we recommend you don’t enable the auto-complete function – a hacked device means they are able to gain access using this method nn**Use a
PIN number on your device.** It’s really important to lock your device when you’re not using it.",,2,20,52,1,2,3,4"
我试图让它小,因为有很多内容,但基本上是上述的字符串,最大的字符串是扰乱我的代码从Banking can save
开始和结束在not using it.
我有几个其他数据相同类型的身体,和总是" body "
内,我一直在试图执行一个函数将从这个CSV字符串内容,为数组或对象数组的数组。
这是我尝试的:
function csv_To_Array(str, delimiter = ",") {
const header_cols = str.slice(0, str.indexOf("n")).split(delimiter);
const row_data = str.slice(str.indexOf("n") + 1).split("n");
const arr = row_data.map(function (row) {
const values = row.split(delimiter);
const el = header_cols.reduce(function (object, header, index) {
object[header] = values[index];
return object;
}, {});
return el;
});
// return the array
return arr;
}
我也想过使用正则表达式,如果它有一个n的逗号,我会分割,虽然如果有一个/"当它找到下一个/":
array.split(/,/n(?!d)/))
试试这个:
csvData.replace(/(rn|n|r)/gm, "");
一旦您使用它来替换或删除新行,下面的代码将帮助您开始理解如何从新的CSV字符串构建数组:
const splitTheArrayAndLogIt = () => {
const everySingleCharacter = csvData.split(""); // <-- this is a new array
console.log(everySingleCharacter);
const splitAtCommas = csvData.split(",");
console.log(splitAtCommas);
}