2 回答
TA贡献2021条经验 获得超8个赞
要简单点的话,就这样:
const oneWeekAll = "{weekStart:2017-11-13,weekEnd:2017-11-19};{weekStart:2017-11-06,weekEnd:2017-11-12};{weekStart:2017-10-30,weekEnd:2017-11-05};";
const result = oneWeekAll.split(';').filter(item => item).map(item => {
const str = item.replace(/\{|\}/g, '')
const arr = str.split(/\:|\,/)
return {
weekStart: arr[1],
weekEnd: arr[3]
}
});
console.log(result);
TA贡献1876条经验 获得超6个赞
const all = "{weekStart:2017-11-13,weekEnd:2017-11-19};{weekStart:2017-11-06,weekEnd:2017-11-12};{weekStart:2017-10-30,weekEnd:2017-11-05};";
const list = all.split(";")
.filter(t => t)
.map(t => t.split(/[{},:]/))
.map(parts => ({
[parts[1]]: parts[2],
[parts[3]]: parts[4]
}));
然后还写了一个比较搞笑的版本(性能肯定不怎么样)
const all = "{weekStart:2017-11-13,weekEnd:2017-11-19};{weekStart:2017-11-06,weekEnd:2017-11-12};{weekStart:2017-10-30,weekEnd:2017-11-05};";
const json = all
.replace(/;?$/, "")
.replace(/,/g, "\",\"")
.replace(/:/g, "\":\"")
.replace(/;/g, ",")
.replace(/\{/g, "{\"")
.replace(/\}/g, "\"}");
const list = JSON.parse(`[${json}]`);
补充一下,上面最后一种肯定是很慢的,不过在 jsPerf 上测试第1种比 @Ash_Shen 的答案慢 35% 左右,尝试把两个 map 合并成一个 map,作用不大,但是改了一个对象的 key,速度一下子就起来了,居然提升了 150% (也就是2.5倍)
const list = all.split(";")
.filter(t => t)
.map(t => {
const parts = t.split(/[{},:]/);
return {
weekStart: parts[2],
weekEnd: parts[4]
};
});
添加回答
举报