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 output
I want to extract only the value where wordId
exists.
Try
const words = Object.entries(data)
.map((item) => item[1].words
.filter((v) => v.wordId)),
);
CodePudding user response:
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);
CodePudding user response:
IIUC,
let data = [
{
id: '...',
words: { id:1, wordId: '0nN1R9AlPGrH67', word: {text:'aa', originalText:'aa'} },
},
{
id: '...',
words: { id:2, wordId:"", word: {text:'aa', originalText:'aa'} },
},
];
const words = data.filter(item => item.words?.wordId !== undefined);
console.log(words)