字符串转JSON

要求快速实现以下要求:


var str = 'a>b and b<c and c=d'


// TODO: 将 `str` 字符串 转成 [{key: 'a', symbol: '>', value: 'b'}] 格式


慕桂英4014372
浏览 382回答 2
2回答

慕容708150

var str = 'a>b and b<c and c=d';var expressions = str.split('and');var regExp = /[+-\\*%/><=]/;var expArray = [];for(var i=0;i<expressions.length;i++){&nbsp; &nbsp; var expression = expressions[i];&nbsp; &nbsp; var keyValue = expression.split(regExp);&nbsp; &nbsp; var item = {};&nbsp; &nbsp; item.key = keyValue[0];&nbsp; &nbsp; item.value = keyValue[1];&nbsp; &nbsp; item.symbol = expression.charAt(expression.search(regExp));&nbsp; &nbsp; expArray.push(item);}console.log(JSON.stringify(expArray));

呼啦一阵风

console.log(str.split('and').map(v => v.trim()).reduce((pre, item) => {&nbsp; &nbsp; const reg = /(.*)([>=<])(.*)/g;&nbsp; &nbsp; const [t, name, symbol, value] = reg.exec(item);&nbsp; &nbsp; return [...pre, {name, symbol, value}];},[]));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript