如何从数据库存储的DraftJS原始数据中获取内容长度?
Hey there! I see you're storing DraftJS editor content as raw JSON in your database and need to calculate the total content length—let me break down the straightforward way to do this, plus some edge cases to watch for.
The Core Approach
DraftJS's raw content structure stores all visible text directly in the text property of each block in the blocks array. So the simplest way to get the total length is to sum up the length of every block's text value.
Example Code
Here's a reusable JavaScript function that handles this, with safeguards against invalid data:
// Sample raw data from your database const draftRawContent = { "blocks": [ {"key": "1m9md", "data": {}, "text": "", "type": "unstyled", "depth": 0, "entityRanges": [], "inlineStyleRanges": []}, {"key": "c8gek", "data": {}, "text": "Lorem ipsum dolor sit amet, eu habitasse magna aliquam non et faucibus, aliquet et ante tempus vestibulum pellentesque, ligula curabi...", "type": "unstyled", "depth": 0, "entityRanges": [], "inlineStyleRanges": []} ] }; // Function to calculate total content length const calculateDraftContentLength = (rawContent) => { // Guard clause: if blocks array doesn't exist or isn't valid, return 0 if (!rawContent?.blocks || !Array.isArray(rawContent.blocks)) { return 0; } // Sum the length of each block's text return rawContent.blocks.reduce((total, block) => { // Ensure we're only working with strings to avoid errors const blockTextLength = typeof block.text === 'string' ? block.text.length : 0; return total + blockTextLength; }, 0); }; // Usage const totalLength = calculateDraftContentLength(draftRawContent); console.log(totalLength); // Outputs the total length of all text in the blocks
Key Notes
- Empty blocks are handled automatically: Blocks with empty
text(like your first example block) contribute 0 to the total length, so no extra checks are needed for those. - Entities and styles don't affect length: Even if you have formatted text (bold, italic) or entities (links, embedded content), the visible text is already included in the block's
textproperty—you don't need to parseentityRangesorinlineStyleRangesfor length calculation. - Safeguards prevent crashes: The function checks if the
blocksarray exists and is valid, and ensuresblock.textis a string before accessing its length. This avoids runtime errors if your database returns unexpected data.
Edge Case: Excluding Specific Block Types
If you ever need to exclude certain block types (e.g., atomic blocks for images that don't have visible text), you can add a condition in the reduce function:
return rawContent.blocks.reduce((total, block) => { // Skip atomic blocks (adjust the type to match your needs) if (block.type === 'atomic') return total; const blockTextLength = typeof block.text === 'string' ? block.text.length : 0; return total + blockTextLength; }, 0);
Hope this solves your problem smoothly! If you run into any weird edge cases with your specific content, feel free to tweak the function to fit your needs.
内容的提问来源于stack exchange,提问作者speak

