53187

How to check if a Map or Set is empty?

<h3>Question</h3>

With a traditional object in JavaScript, it is easy enough to check if it is empty using the Object.keys method:

const emptyObj = {}; console.log(Object.keys(emptyObj).length === 0); // true, i.e. "empty" const populatedObj = { foo: 'bar' }; console.log(Object.keys(populatedObj).length === 0); // false, not empty

Although a bit redundant, you can use the same approach with arrays too if you like:

const emptyArr = []; console.log(Object.keys(emptyArr).length === 0); // true const populatedArr = [1, 2, 3]; console.log(Object.keys(populatedArr).length === 0); // false

However, ES6's handy new data structures <em>Map</em> and <em>Set</em>, don't work the same way. If you try to use Object.keys on them you will <em>always</em> get an empty array!

const populatedSet = new Set(['foo']); console.log(Object.keys(populatedSet).length); // 0 const populatedMap = new Map([['foo', 1]]); console.log(Object.keys(populatedMap).length); // 0

So what is the best way to check whether or not your fancy new ES6 structures are populated? Also, is there some sort of single overloaded method that would work for objects, arrays, Maps, <em>and</em> Sets?


<h3>Answer1:</h3>

You use its size property. Both Maps and Sets have it (here and here).

<pre class="snippet-code-js lang-js prettyprint-override">const populatedSet = new Set(['foo']); console.log(populatedSet.size); // 1 const populatedMap = new Map([['foo', 1]]); console.log(populatedMap.size); // 1

(Side note: WeakMaps and WeakSets don't have size or several other features their "strong" counterparts have, in order to keep their implementations, and code using them, sane. :-) Where they have similar functionality, they offer the same API, but they aren't subclasses.)


<h3>Answer2:</h3>

You can do this directly

if(storeMapDetails.size==0)//Do something YOu can check this directly


<h3>Answer3:</h3>

For both cases you can use

const populatedSet = new Set(['foo']); console.log(populatedSet.size); // should be 1

来源:https://stackoverflow.com/questions/55520583/how-to-check-if-a-map-or-set-is-empty

Recommend

  • Amazon S3 Signed Url is not working with Office Web Apps Viewer (encodeURIComponent not working)
  • AmCharts duplicates date (x-axis) for points of different categories but same date
  • Can testing with real adMob ads after the app's development results in adMob's policy viol
  • How to add a Contact in Contact using iPhone Native UI
  • python, UnicodeEncodeError, converting unicode to ascii
  • In C++ how to best decouple 2 classes that must maintain collections of references to each other
  • visual studio (SSDT) 2017 unable to start debugging
  • After upgrade to GIT bash 2.8.2, cannot run sqlite3
  • How to access images in UIATablecell
  • How can I configure security per node in Corda using Gradle?
  • Calling a method from within a synchronized method
  • How to add a character like (“,” , “[” , “]”) at the end of a JSON-Object
  • Generically overloading operator new while considering alignment requirements
  • Oracle outer join with filter condition on the second table
  • How to create jQuery datatable with multiple child rows(nested table)?
  • Removing spaces after and before commas (not between words) using command line
  • NSTimers causing leaks
  • How to get list of all user CA certificates installed in an Android Device?
  • Hadoop MapReduce sort reduce output using the key
  • How do we add new button to gmail compose bar in chrome extension? Is it through javascript or some
  • Get Network Interface Names and Set All to DHCP Batch Script
  • How to get delivery report for a specific contact number while sending sms to multiple contacts in a
  • I am trying to create an app in android to insert data into sql server through a web service.
  • GAE python NDB projection query working in development but not in production
  • Javapackager tool from command-line on OSX?
  • Call a specific instance of a service in Azure Service Fabric
  • Intersection of characters in two strings
  • Salesforce API: How to identify a Case from an email reference code (“[Ref: … :Ref]”)?
  • Identify File Type in Java
  • Enable CORS on Tomcat 8.0.30
  • Get spring boot pagination number starts from 1 instead of 0
  • Use 2D Text into 3D scenes in JavaFX results in blurry texts
  • How to get File path from pdfUri obtained from PDF chooser intent library, in onActivityResult call
  • Failed to resolve: firebase-auth-15.0.0 [closed]
  • Find all parks for a given zipcode with google maps
  • Stop an element moving with padding on hover
  • Thumbnails for mxml components in Flex
  • Bad automatic Triangulation with Mayavi for coloring a surface known only by its corner
  • Cross compile glibc for arm, got undefined reference to some unwind functions