我想知道将此字符串转换为JavaScript中的对象的最有效方法。
这是丑陋的字符串:
"\"date\",\"initRegistrations\",\"registrations\",\"finalizeRegistrations\"\r\n\"03/29/2017\",\"0\",\"0\",\"0\"\r\n\"03/30/2017\",\"5\",\"4\",\"4\"\r\n\"03/31/2017\",\"42\",\"0\",\"0\"\r\n\"04/01/2017\",\"192\",\"0\",\"0\"\r\n\"04/02/2017\",\"4\",\"0\",\"0\"\r\n\"04/03/2017\",\"23\",\"0\",\"0\"\r\n\"04/04/2017\",\"5\",\"0\",\"0\"\r\n"
目前我正在使用此功能,但它不能正常工作,预期输出将是对象的对象,其中包含密钥date,initRegistrations,registrations,finalizeRegistrations:
function convertToArrayOfObjects(data) {
var keys = data.shift(),
i = 0, k = 0,
obj = null,
output = [];
for (i = 0; i < data.length; i++) {
obj = {};
for (k = 0; k < keys.length; k++) {
if(data[i][k]){
obj[keys[k]] = data[i][k];
}
}
output.push(obj);
}
return output;
}
有没有任何奇特的方法可以轻松实现这一点,或者我应该去玩我的对象数组? 任何帮助或建议表示赞赏。 感谢。
答案 0 :(得分:0)
您可能正在寻找拆分,这会使字符串中出现数组:
var a = s.split("\r\n");
这将为您提供字符串所包含的行数组。然后,如果您需要每行中的字段,则可以在for循环中使用另一个分隔符(逗号?)进行进一步的拆分。
var tbl=[];
var rows = s.split("\r\n");
for(var y in rows) {
var row = rows[y].split('"');
tbl.push(row);
}
这将为您提供一组数组。只需很少的努力,您可以改进它以识别带有字段名称的标题行,然后将它们用作每行的键。 (注意:我现在正在移动设备上使用,所以这是我能为您做的最好的,但如果您仍然丢失,我可以在稍后向您展示更详细的示例。)
答案 1 :(得分:0)
可能对某些人来说太功能了,但这就是我写它的方式。
const s = "\"date\",\"initRegistrations\",\"registrations\",\"finalizeRegistrations\"\r\n\"03/29/2017\",\"0\",\"0\",\"0\"\r\n\"03/30/2017\",\"5\",\"4\",\"4\"\r\n\"03/31/2017\",\"42\",\"0\",\"0\"\r\n\"04/01/2017\",\"192\",\"0\",\"0\"\r\n\"04/02/2017\",\"4\",\"0\",\"0\"\r\n\"04/03/2017\",\"23\",\"0\",\"0\"\r\n\"04/04/2017\",\"5\",\"0\",\"0\"\r\n";
// Remove surrounding quotes from a string.
const removeQuotes = s => s.replace(/^"|"$/g, '');
// Split input by newline ('\r\n')
const lines = s.trim().split('\r\n');
// Get header (first line of input) and remove quotes.
const header = lines[0].split(',').map(removeQuotes)
// The rest of the string is data. Split by comma and remove quotes.
const data = lines.splice(1).map(line => line.split(',').map(removeQuotes));
// Given header row and data row, combine into an object.
const zipWith = header => row => {
return header.reduce((map, item, index) => {
map[item] = row[index];
return map;
}, {});
}
// Now process all your data with a map :)
const result = data.map(zipWith(header));
console.log(result);
&#13;
非常确定输出正是您想要的:
[
{
"date": "03/29/2017",
"initRegistrations": "0",
"registrations": "0",
"finalizeRegistrations": "0"
},
{
"date": "03/30/2017",
"initRegistrations": "5",
"registrations": "4",
"finalizeRegistrations": "4"
},
{
"date": "03/31/2017",
"initRegistrations": "42",
"registrations": "0",
"finalizeRegistrations": "0"
},
{
"date": "04/01/2017",
"initRegistrations": "192",
"registrations": "0",
"finalizeRegistrations": "0"
},
{
"date": "04/02/2017",
"initRegistrations": "4",
"registrations": "0",
"finalizeRegistrations": "0"
},
{
"date": "04/03/2017",
"initRegistrations": "23",
"registrations": "0",
"finalizeRegistrations": "0"
},
{
"date": "04/04/2017",
"initRegistrations": "5",
"registrations": "0",
"finalizeRegistrations": "0"
}
]