Filtering text according to indices and color words in React

Viewed 191

I have the following JsonData:

{
    "text": "This is the text with many words",
    "annotation": [{
            "comment": "Comment A",
            "indices": [0, 3]
        },
        {
            "comment": "Comment B",
            "indices": [1, 2, 4]
        }
    ]
}

I'd like to color words that belong to each comment so that

"This", "text"  ---> Red

and

"is", "the", "with" ---> blue.
  1. I think it requires some filter or map function but I can't imagine it so I ask for a suggestion on how to "iterate" over words, and then over comments, and then over indices. (or maybe in a different order?)

  2. I'd like to do it in React app. Is this the correct place for these calculations?

Code:

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

I am new to javascript, react, and functional programming so any suggestions will be helpful, thanks.

2 Answers

In your .map function you can get the index :

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

So you can compare your index with your array of index like this :

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

Firstly, You can build index_mapping with the content structure that looks like

[{"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}]

Secondly, You can use Array#map to concatenate all words matching with 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});


It should be processed after fetching data, you have jsonData then normalize data like my answer. After that, you can render components as you wish. Good luck !

Related