["name: edward, subjectId:1, remark:passed",
"name: edward, subjectId:3, remark:passed",
"name: Jamie, subject:1, remark:excellent"]
上面是一个混乱的输出,我无法控制。我必须将它映射并清理干净。理想的数组对象必须如下所示:
[{name:"edward",subjectId:1,3,remark:"passed},{name:"Jamie",subjectId:1,remark:"excellent"}]
但对我来说似乎不可能,因为它没有每条记录的唯一ID。我可以比较注释并正确分组subjectId,但是如果它在同一日期插入了一行呢?然后我的逻辑有缺陷。有什么想法吗?
答案 0 :(得分:0)
尝试使用Array.prototype.map()
; String.prototype.replace()
与RegExp
/(\w+)(?=:|,|$)/g
":"
匹配后跟","
,JSON.parse()
或字符串结尾的字词,替换为带引号的字符串; var arr = ["name: edward, subjectId:1, remark:passed",
"name: edward, subjectId:3, remark:passed",
"name: Jamie, subject:1, remark:excellent"
];
var res = arr.map(function(val) {
return JSON.parse("{" + val.replace(/(\w+)(?=:|,|$)/g, "\"$1\"") + "}")
});
console.log(res);
document.querySelector("pre").textContent = JSON.stringify(res, null, 2)
<pre></pre>
&#13;
<input type="radio" name="position" id="left">
<input type="radio" name="position" id="center">
<input type="radio" name="position" id="right">
&#13;
答案 1 :(得分:0)
你的输入非常接近JSON,你不得不抛弃字符串操作!
var input = [
"name: edward, subjectId:1, remark:passed",
"name: edward, subjectId:3, remark:passed",
"name: Jamie, subject:1, remark:excellent"
];
function makeJson(str) { // Deal with each of your input strings
function wrapKeyAndVal(str) { // Wrap the key and value pairs in double quotes
var key = str.split(':')[0].trim();
var val = str.split(':')[1].trim();
return '"' + key + '"' + ':' + '"' + val + '"';
}
return str.split(',').map(wrapKeyAndVal).join(',');
}
input = input.map(makeJson);
// Parse each string into an object
var output = input.map(item => JSON.parse("{" + item + "}"))
// You'll end up with an array of objects
console.log(output);