例如,我有一串文字
var dateString = "2018/09/12";
var regex = /^\d{4}\/((0\d)|(1[012]))\/(([012]\d)|3[01])$/;
if (regex.test(dateString)) {
return true;
} else {
return false;
}
我还有一个实体
"{"Date": 01/01/2019, "0": "John", "1": "Jack", "3": "Tom", "4": "Will", "5": "Joe"}"
是否可以将文本字符串转换为实体?例如,
function demo(first, second) {
this.first = first,
this.second = second
}
转到"Date"
first
转到01/01/2019
second
转到"0"
first
排名第二
答案 0 :(得分:3)
您可以创建自己的class
,然后创建在json对象上迭代的对象
class CustomObject {
constructor(x, y) {
this.first = x;
this.second = y;
}
}
// your initial data as a json into a string
const str = '{"Date": "01/01/2019", "0": "John", "1": "Jack", "3": "Tom", "4": "Will", "5": "Joe"}';
// transform your string into a json object
const json = JSON.parse(str);
// Build the custom objects, using the data inside of the json object
// The notation [x, y] is called -> destructuring
const objs = Object.entries(json).map(([x, y]) => new CustomObject(x, y));
// Now that we have the objects, display the values stored inside
// each one of them, to show they are correctly settled
objs.forEach(x => console.log(x.first, x.second));
答案 1 :(得分:0)
Object.keys(json)
将与map
函数结合使用:
const str = '{"Date": "01 / 01 / 2019", "0": "John", "1": "Jack", "3": "Tom", "4": "Will", "5": "Joe"}';
const json = JSON.parse(str);
function demo(first, second) {
console.log(first, second);
this.first = first,
this.second = second
}
Object.keys(json).map(key => {
demo(key, json[key]);
});