Question:
I’m going to use the code below. But I’m not sure it’s readable.I wonder if there is a code style commonly used in method chaining that improves the readability of this code. (like indentation, line breaks, etc.)
Question
How to increase this code’s readability? Any recommendation?
const words = Object.entries(data).map((item) => item[1].words.filter((v) => v.wordId)));
Input data//data looks like this
[
{
id: '...',
words: { id:1, wordId: '0nN1R9AlPGrH67', word: {text:'aa', originalText:'aa'} },
},
]
Expected outputI want to extract only the value where
wordId
exists.Try
const words = Object.entries(data)
.map((item) => item[1].words
.filter((v) => v.wordId)),
);
Answer:
As a suggestion, instead of writing a one line chain, you could break it down into multiple variables and combine them. This should increase code modularity and make it more readable. See an example below:const objData = Object.entries(data);
const callbackFilter = (item) => item[1].words.filter((v) => v.wordId);
const dataArray = objData.map(callbackFilter);
If you have better answer, please add a comment about this, thank you!