将包含标签的简单描述数据转换为数组

时间:2018-12-10 06:34:50

标签: arrays string reactjs react-native

我有类似的描述数据:

"<question> This is question 1? </question> 
<answer> This is answer 1 </answer>
<question> this is question 2? </question>
<answer> This is answer </answer>"

所需的输出为:

 desc= {
   [question: "This is question 1?", answer: "This is answer 1"], 
   [question: "this is question 2?", answer: "This is answer 2] 
 }

1 个答案:

答案 0 :(得分:1)

检查一下:

const desc = "<question> This is question 1? </question><answer> This is answer 1 
</answer><question> this is question 2? </question><answer> This is answer </answer>";

var questions = desc.match(/<question>(.*?)<\/question>/g).map(function(val){
return val.replace(/<\/?question>/g,'');
});

var answers = desc.match(/<answer>(.*?)<\/answer>/g).map(function(val){
return val.replace(/<\/?answer>/g,'');
});

var arrayList = questions.map((item,index) => {
return {question:item, answer: answers[index]}
})

console.log(JSON.stringify(arrayList));

工作解决方案:

https://codepen.io/anon/pen/NeWEdz