57028

Get count of elements in javascript object where key=option

Question:

This is a javascript object.<br /> How can I get the count of elements with condition <strong>gallery="Abstract"</strong> and <strong>gallery="Game"</strong>.

window.paintings = { 1: { id: 1, name: 'Abstract 1', gallery: 'Abstract', src:'Image64.jpg' }, 2: { id: 2, name: 'Abstract 2', gallery: 'Abstract', src:'Image65.jpg' }, 3: { id: 3, name: 'Abstract 3', gallery: 'Abstract', src:'Image66.jpg' }, 4: { id: 1, name: 'Game 1', gallery: 'Game', src:'Image66.jpg' }, 5: { id: 2, name: 'Game 2', gallery: 'Game', src:'Image66.jpg' }, };

Answer1:

If you want to iterate over the object:

p = { 1: { id: 1, name: 'Abstract 1', gallery: 'Abstract', src:'Image64.jpg' }, 2: { id: 2, name: 'Abstract 2', gallery: 'Abstract', src:'Image65.jpg' }, 3: { id: 3, name: 'Abstract 3', gallery: 'Abstract', src:'Image66.jpg' }, 4: { id: 1, name: 'Game 1', gallery: 'Gme', src:'Image66.jpg' }, 5: { id: 2, name: 'Game 2', gallery: 'Game', src:'Image66.jpg' }, }; var count = 0; for (var key in p) { if (p.hasOwnProperty(key)) { if(p[key].gallery === "Abstract" || p[key].gallery === "Game") count++; } }

Answer2:

Just a sample output. Modify it as per your requirement.

<pre class="snippet-code-js lang-js prettyprint-override">var paintings = { 1: { id: 1, name: 'Abstract 1', gallery: 'Abstract', src:'Image64.jpg' }, 2: { id: 2, name: 'Abstract 2', gallery: 'Abstract', src:'Image65.jpg' }, 3: { id: 3, name: 'Abstract 3', gallery: 'Abstract', src:'Image66.jpg' }, 4: { id: 1, name: 'Game 1', gallery: 'Game', src:'Image66.jpg' }, 5: { id: 2, name: 'Game 2', gallery: 'Game', src:'Image66.jpg' }, }; var count = 0; for (var property in paintings) { if (paintings.hasOwnProperty(property)) { if (paintings[property]['gallery'] == 'Abstract' || paintings[property]['gallery'] == 'Game' ) { count++; } } } alert(count);

Answer3:

Try this:

var AbstractCount=0; var GameCount=0; window.paintings = { 1: { id: 1, name: 'Abstract 1', gallery: 'Abstract', src:'Image64.jpg' }, 2: { id: 2, name: 'Abstract 2', gallery: 'Abstract', src:'Image65.jpg' }, 3: { id: 3, name: 'Abstract 3', gallery: 'Abstract', src:'Image66.jpg' }, 4: { id: 1, name: 'Game 1', gallery: 'Game', src:'Image66.jpg' }, 5: { id: 2, name: 'Game 2', gallery: 'Game', src:'Image66.jpg' }, }; for(keys in window.paintings){ if(window.paintings[keys].gallery == 'Abstract'){ AbstractCount++; } else if(window.paintings[keys].gallery == 'Game'){ GameCount++; } } alert(AbstractCount); alert(GameCount);

Answer4:

The most straightforward way is using native functions:

// This is a reusable function to count elements in object // based on some function var countElements = function(obj, condition) { return Object.keys(obj).filter(function(key) { if (obj.hasOwnProperty(key)) { var item = obj[key]; return condition(obj[key]); } }).length; }; var count = countElements(window.paintings, function(item) { // Return true from here if you want to count particular element return item.gallery == 'Abstract' || item.foo == 'Game'; // you can add more conditions here. }); alert(count); // Alerts "3"

Answer5:

Try use jquery grep.

Change your object to an array do it, like this.

var arr = [ { id: 1, name: 'Abstract 1', gallery: 'Abstract', src:'Image64.jpg' }, { id: 2, name: 'Abstract 2', gallery: 'Abstract', src:'Image65.jpg' }, { id: 3, name: 'Abstract 3', gallery: 'Abstract', src:'Image66.jpg' }, { id: 1, name: 'Game 1', gallery: 'Game', src:'Image66.jpg' }, { id: 2, name: 'Game 2', gallery: 'Game', src:'Image66.jpg' } ]; var x = $.grep(arr, function( n, i ) { return (n.gallery == 'Abstract' || n.gallery == 'Game'); }); $("#result").html(x.length);

<a href="http://jsfiddle.net/Menda0/58dp9dpr/" rel="nofollow">Jsfiddle here</a>

Answer6:

Use a for loop to iterate over the array ...

EDIT: but I just notice that it's not an array, but it's a Javascript object. Arrays are recognizable because of the straight brackets ([]), while this has curly brackets ({}) So the below code snippet will NOT work on this.

var count = 0; for (var i = 0; i < window.paintings.length; i++) { var item = window.paintings[i]; if (...) { count = count + 1; } }

Something like this should work:

for (var property in object) { if (object.hasOwnProperty(property)) { // do your logic here } }

Recommend

  • Prevent reloading page after submiting form. ( no ajax )
  • Is there any way to distinguish between an unset property and a property set to undefined? [duplicat
  • Ember-data “Cannot call method 'hasOwnProperty' of undefined”
  • How do I iterate over this json structure to produce another structure?
  • Decimal to Binary in C
  • How to version control out-of-source build directory using CMake and SVN
  • Javascript remove duplicate values from array of objects
  • IsOrderedBy Extension Method
  • How to create L lists of n non-zero random decimals where each list sums to 1.0?
  • How to run requests.get asynchronously in Python 3 using asyncio?
  • How to notify a specific thread in Java
  • Redis under Classic ASP(VBScript)
  • How to autopopulate a field in SugarCRM form
  • Reading a file into a multidimensional array
  • Android application: how to use the camera and grab the image bytes?
  • How to use JavaScript to determine whether a file exists in a directory?
  • OOP Javascript - Is “get property” method necessary?
  • Functions in global context
  • Database structure design with variable amounts of fields
  • How to clear text inside text field when radio button is select
  • Scrapy recursive link crawler
  • FileReader+canvas image loading problem
  • Why value captured by reference in lambda is broken? [duplicate]
  • Master page gives error
  • How do I fake an specific browser client when using Java's Net library?
  • How to get a value (ex: baseURL) in every Karate feature?
  • Deserializing XML into class C#
  • Redux, normalised entities and lodash merge
  • Function pointer “assignment from incompatible pointer type” only when using vararg ellipsis
  • Compare two NSDates in iPhone
  • How to delete a row from a dynamic generate table using jquery?
  • using HTMLImports.whenReady not working in chrome
  • Why joiner is not used after Sequence generator or Update statergy
  • Authorize attributes not working in MVC 4
  • python draw pie shapes with colour filled
  • EntityFramework adding new object to nested object collection
  • Checking variable from a different class in C#
  • Recursive/Hierarchical Query Using Postgres
  • How to Embed XSL into XML
  • UserPrincipal.Current returns apppool on IIS