根据React中的索引和颜色词过滤文本



我有以下JsonData:

{
"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

"is", "the", "with" ---> blue.
  1. 我认为它需要一些过滤器或映射功能,但我无法想象,所以我询问了如何";迭代";超过单词,然后超过评论,然后超过索引。(或者可能以不同的顺序?(

  2. 我想在React应用程序中完成。这是进行这些计算的正确地点吗?

代码:

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>
)
}

我是javascript、react和函数式编程的新手,所以任何建议都会很有帮助,谢谢。

首先,您可以使用类似的内容结构构建index_mapping

[{"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_mapping匹配的单词

const data = {
"text": "This is the text with many words",
"annotation": [{
"comment": "Comment A",
"indices": [0, 3]
},
{
"comment": "Comment B",
"indices": [1, 2, 4]
}
]
};
const index_mapping = data.text.split(" ").map((txt, index) => ({txt, index}));
const words_in_red_color = data.annotation[0].indices.map(numeric_index => index_mapping.find(r => r.index === numeric_index)?.txt);
const words_in_blue_color = data.annotation[1].indices.map(numeric_index => index_mapping.find(r => r.index === numeric_index)?.txt);
console.log({words_in_red_color, words_in_blue_color});


它应该在获取数据后进行处理,您有jsonData,然后像我的答案一样规范化数据。之后,可以根据需要渲染组件。祝你好运

.map函数中,您可以获得索引:

[1,2,3].map((value, index) => {...})

所以你可以将你的索引与你的索引数组进行比较,如下所示:

jsonData.split(" ").map((value, index) => {
if (jsonData.annotation[0].indices.includes(index)) {
// this is the annotation [0]
}
if (jsonData.annotation[1].indices.includes(index)) {
// this is the annotation [1]
}
})

最新更新