Trouble with recursive function iteration on object properties

What's causing the alert to display only 1?


function test() {
 var myobj = {
  a : 'Cool stuff',
  b : 'findtheanswer',
  c : {
    aa : 'Even cooler things',
    bb : 'findtheanswer',
    cc : {
     aaa : 'The coolest item',
     bbb : 'findtheanswer'
    }
   }
 }
 function countOccurrences(needle, haystack) {
  var count = count || 0;
  for(var i in haystack) {
   if (typeof(haystack[i]) == 'object') {
    countOccurrences(needle, haystack[i]); 
   } else {
    if (needle == haystack[i]) {
     count++; 
    }
   }
  }
  return count;
 }
 alert(countOccurrences('findtheanswer', myobj));
}

Answer №1

Make sure to always remember the count when making a recursive call.

function example() {
 var data = {
  alpha : '1st level property',
  beta : 'searchme',
  gamma : {
    delta : '2nd level property',
    epsilon : 'searchme',
    zeta : {
     eta : '3rd level property',
     theta : 'searchme'
    }
   }
 }
 function countOccurrences(target, source) {
  var occurrenceCount = 0;
  for(var key in source) {
   if (typeof(source[key]) == 'object') {
    occurrenceCount = occurrenceCount + countOccurrences(target,source[key]); 
   } else {
    if (target == source[key]) {
     occurrenceCount++; 
    }
   }
  }
  return occurrenceCount;
 }
 alert(countOccurrences('searchme',data));
}

Answer №2

the reason count gets reset is because every time you invoke the function countem, it resets the variable count.

if (typeof(haystack[i]) == 'object') {
    count += countem(needle,haystack[i]);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Display the image button when a hyperlink is clicked using JavaScript and VB.NET

I'm just starting out with JavaScript and could really use some help. Here's the situation: I have a group of hyperlinks that are supposed to show an image when clicked, but it isn't working. Can someone assist me? <td> <asp:Hy ...

NodeJS Like/Dislike System: Leveraging the Power of NodeJS

(Please refer to my solution in the answer post below) Hello there! Today, I have a question about implementing a like/dislike system using nodeJs with data stored in MongoDB. What is the current scenario? I'm tasked with creating the backend for ...

Encountering 404 errors on dynamic routes following deployment in Next.JS

In my implementation of a Next JS app, I am fetching data from Sanity to generate dynamic routes as shown below: export const getStaticPaths = async () => { const res = await client.fetch(`*[_type in ["work"] ]`); const data = await re ...

The dropdown menu is displaying the initial value from the JSON file rather than the expected default text

Operation.. Users need to choose the items displayed in a dropdown menu, which are read from a JSON file. The dropdown menu should initially show a default text of "Please select shops..." before displaying the item names. Challenge: The default text of ...

Display a single submenu on mouseover using Javascript

Hello there, I have been working on creating a small menu using only Javascript, but I am facing an issue where the onmouseover event is displaying all submenus instead of just one. Below is the section of code that is supposed to change style.display to ...

Having trouble generating a mock constructor for the user model

While attempting to simulate my user model in order to test my service, the nest console is throwing a TypeError. I am unsure of how to properly 'emulate' the constructor of the user model. user.service.spec.ts import { Test, TestingModule } fro ...

Looking for a way to convert 24-hour format to minutes in Angular? I'm in need of some TypeScript code to

I am looking for Typescript code that can convert 24-hour time format into minutes. For example, when converting 1.00 it should output as 60 minutes. When converting 1.30 it should equal to 90 minutes. If anyone has the code for this conversion, p ...

Allowing Angular2 Components and their Sub Components to access a shared instance of ngModel within a service

Currently, I have been working on constructing a complex view that requires multiple functionalities. To ensure proper organization, I have divided it into various custom components. I don't want to go into great detail, but I have managed to make it ...

Modifying the font style within an ePub document can affect the page count displayed in a UIWebView

Currently in the development phase of my epubReader app. Utilizing CSS to customize the font style within UIWebView, however encountering a challenge with the fixed font size causing fluctuations in the number of pages when changing the font style. Seeki ...

Using JQuery to extract the value of cells

How to retrieve cell values using JQuery? I attempted the following code: $("#table tr").each(function(){ var result = $(this).find("td:first").html(); alert(result); }); However, instead of individual values, it returns a string comprising all ...

Implementing ngFor to Iterate Through a JSON Object in Angular 6

Iterate through the object list retrieved from a JSON object Here is the JSON object that I have fetched: { "0": { "0": null, "1": "Consolidated Statements of Changes in Stockholders\u2019 Deficit", "2": null, "3": "", "4": "" ...

Even when I try to access the properties of the arguments object, it remains empty and has a zero

Why is the arguments object showing a length of zero when I pass parameters to the function, even though I can still access its properties? I am referring to the arguments object that is implemented by all JavaScript functions, allowing you to access the f ...

vue-awesome-swiper / The button's name is synchronized, causing all other swiper elements to move in unison

<template> <swiper v-for="item in items" :key="item.id" :options="swiperOption" ref="mySwiper" @someSwiperEvent="callback"> <swiper-slide>I'm Slide 1</swiper-slide> <swiper-slide>I'm Slide 2</swiper-slid ...

Retrieving every piece of information from Kendo Grid's data source

After following a tutorial on exporting Kendo Grid Data, I am now attempting to export all data, not just the data shown on the page. How can I accomplish this task? I attempted to change the page size before retrieving the data: grid.dataSource.pageSize ...

Creating images or PDFs from HTML with CSS filters: a guide

Looking for someone who has experience creating images or PDFs from HTML code. The HTML contains images with CSS filters such as sepia and grayscale. If you have worked on this type of project before, I would love to hear about your experience. <img cl ...

Exploring the jQuery Solution for Enhancing Dojo Widget Framework

My experience with Dojo in the past has been great, especially with its widget infrastructure. Being able to easily separate code and HTML content, having a seamless connection with the require system used by Dojo, and the convenient builder that compresse ...

Tips for concealing images within a designated list and revealing them in a separate list

I have a question regarding image visibility. Is it possible to hide certain images from a "SHOW ALL" list, but have them appear in a different category list? Below is the code snippet: <section> <ul class="portfolio_filters"> < ...

Strategies for Handling a High Volume of API Requests in Node JS

My journey with Node JS began recently, and I had a smooth start. I followed an online tutorial and successfully accepted a GET request in my server.js file. Coming from a Java background, I found myself with a handful of questions that I couldn't fi ...

dealing with errors coming from a child asynchronous callback function

function main(){ try { subCallbackFunction(1,(err,res) =>{ if(err){ throw Error(err); } }) } catch (e) { /// Handling error from subCallbackFunction inside this catch block ////// conso ...

Is there a chart tool that allows for editing graphs by simply dragging points?

Currently, I am in search of a charting library that is preferably JavaScript-based (although Flash could work as well) and has the capability to display time series data as a line chart. Additionally, I need this library to allow users to drag points on t ...