Javascript 根据React中的索引和颜色词过滤文本
我有以下JsonData:Javascript 根据React中的索引和颜色词过滤文本,javascript,arrays,reactjs,Javascript,Arrays,Reactjs,我有以下JsonData: { "text": "This is the text with many words", "annotation": [{ "comment": "Comment A", "indices": [0, 3] }, { "
{
"text": "This is the text with many words",
"annotation": [{
"comment": "Comment A",
"indices": [0, 3]
},
{
"comment": "Comment B",
"indices": [1, 2, 4]
}
]
}
我想给每个评论的单词涂上颜色,这样
"This", "text" ---> Red
及
导出默认函数PrettyPrint({jsonData}){
返回(
{jsonData&&jsonData.text.split('').map((行)=>(
线
//为每种颜色过滤单词的函数应该在这里吗?
))}
)
}
我不熟悉javascript、react和函数式编程,因此任何建议都会很有帮助,谢谢。在您的
.map
函数中,您可以获得索引:
[1,2,3].map((值,索引)=>{…})
因此,您可以将索引与索引数组进行比较,如下所示:
jsonData.split(“”).map((值,索引)=>{
if(jsonData.annotation[0].index.includes(index)){
//这是注释[0]
}
if(jsonData.annotation[1].index.includes(index)){
//这是注释[1]
}
})
首先,您可以使用如下内容结构构建索引映射
[{"txt":"This","index":0},{"txt":"is","index":1},{"txt":"the","index":2},{"txt":"text","index":3},{"txt":"with","index":4},{"txt":"many","index":5},{"txt":"words","index":6}]
其次,您可以使用Array#map
将所有与index_映射匹配的单词连接起来
const数据={
“文本”:“这是包含许多单词的文本”,
“注释”:[{
“评论”:“评论A”,
“指数”:[0,3]
},
{
“评论”:“评论B”,
“指数”:[1,2,4]
}
]
};
const index_mapping=data.text.split(“”.map((txt,index)=>({txt,index}));
const words\u in\u red\u color=data.annotation[0].index.map(数值索引=>索引映射.find(r=>r.index==数值索引)?.txt);
const words_in_blue_color=data.annotation[1].index.map(数值索引=>索引映射.find(r=>r.index==数值索引)?.txt);
log({words\u in\u red\u color,words\u in\u blue\u color})代码>这是否回答了您的问题?如果你需要帮助,请告诉我@大卫1992是的,它确实帮助了我,我想我明白了。但是,我不知道如何在react组件中使用此代码。我的jsonData
是通过一些API获取的。有什么想法吗?它应该在获取数据后处理,还是在组件中处理?这肯定很有帮助,但我的问题与React中的这种情况有关,因此它不能完全回答问题。它应该在获取数据后处理,您有jsonData
,然后像我的答案一样规范化数据。之后,您可以按照自己的意愿呈现组件@davids1992是否可以将此注释添加到您的答案中?那么答案就完整了。除了一个例外:处理应该在后端完成,我认为这是因为useEffect不会等待来自API的数据,并且在试图修改尚未获取的值时会抛出错误。
export default function PrettyPrint({ jsonData }) {
return (
<div>
{jsonData && jsonData.text.split(' ').map((line) => (
line
// Should the function that filters words for each color be here?
))}
</div>
)
}
[{"txt":"This","index":0},{"txt":"is","index":1},{"txt":"the","index":2},{"txt":"text","index":3},{"txt":"with","index":4},{"txt":"many","index":5},{"txt":"words","index":6}]