TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Why I Like Using Maps (and WeakMaps) for Handling DOM Nodes

91 pointsby joelkeslerabout 2 years ago

7 comments

kevincoxabout 2 years ago
I would argue that all &quot;mapping&quot; structures should use Map these days. Objects should be used only for record&#x2F;struct data with a fixed set of programmer-named keys.<p>I think MDN has a good comparison: <a href="https:&#x2F;&#x2F;developer.mozilla.org&#x2F;en-US&#x2F;docs&#x2F;Web&#x2F;JavaScript&#x2F;Reference&#x2F;Global_Objects&#x2F;Map#objects_vs._maps" rel="nofollow">https:&#x2F;&#x2F;developer.mozilla.org&#x2F;en-US&#x2F;docs&#x2F;Web&#x2F;JavaScript&#x2F;Refe...</a><p>The only real downside of maps is that they don&#x27;t support JSON serialization. However you can fix this pretty easily by using a map with an overridden `toJSON` for serializable keys.<p><pre><code> class StringMap extends Map { toJSON() { return Object.fromEntries(this); } }</code></pre>
评论 #35836674 未加载
评论 #35839036 未加载
评论 #35839687 未加载
评论 #35837103 未加载
akira2501about 2 years ago
Why not just use the &#x27;dataset&#x27; property of the element itself? Then you can use querySelectorAll to find your selected rows automatically:<p><pre><code> node.querySelectorAll(&#x27;tr[data-selected=&quot;true&quot;]&#x27;); </code></pre> In other words.. &quot;use the DOM to handle the DOM.&quot;
评论 #35836602 未加载
geuisabout 2 years ago
This might be one of the more interesting articles I&#x27;ve read in a few years that deal with low level direct DOM manipulation vs &quot;yet another thing about React&quot;.
评论 #35836003 未加载
globalise83about 2 years ago
Nice! I have used Maps often for storing arbitrary key-value pairs, but until 5 minutes ago I didn&#x27;t know you could use object references as keys. So this was a very good use of 5 mins.
评论 #35838845 未加载
rektideabout 2 years ago
I need to read &amp; consider this more, but my word, putting data <i>in</i> the DOM is so divine, is so the web way. See, HTML is the Web, <a href="https:&#x2F;&#x2F;www.petelambert.com&#x2F;journal&#x2F;html-is-the-web" rel="nofollow">https:&#x2F;&#x2F;www.petelambert.com&#x2F;journal&#x2F;html-is-the-web</a>
评论 #35839981 未加载
JoeSlothabout 2 years ago
This is great for some use cases, but in situations like a very large list mentioned in the article it’s likely that a real world app would be virtualizing the nodes.. which would make an id a more stable key than a dom node.
eviksabout 2 years ago
Why did they not make the map assigning syntax as convenient as with objects, instead going for the clunky get&#x2F;set?
评论 #35839017 未加载
评论 #35839139 未加载