Exploring the depths of object recursion: a guide to looping endlessly

What is the method to retrieve all values from an object and compare them?

Object :

obj = {
     a : 10,
     b : [{b1 : 101 , b2:201},{b3 : 102 , b4:204}],
     c : [{c1 : 107 , c2:209 ,d :[{d1:109},{d2:402}]}
}

function compareValues(101,obj) {           

   if (retrieveValueFromObject(obj,101)) {
       return true;
   } else {
      return false;
   } 

   function comparator(a, b) {
       return ('' + a).toLowerCase().indexOf(('' + b).toLowerCase()) > -1;
   }
}

Pending: retrieveValueFromObject() needs to be implemented in a way that it loops through all key-value pairs in the object and returns a flag (true/false) if the value is found in the object.

Answer №1

Here is a possible solution:

function checkValueInObject(obj, value) {
  for(let key in obj) {
      if(obj[key] == value) {
        return true;
      }
      if(typeof obj[key] === 'object' || Array.isArray(obj[key]))
       return checkValueInObject(obj[key], value);
  }
  return false;
}

I came across this code snippet on:

Answer №2

attempt:

function getValueFromObject(obj,101) {
    var outcome;
    for (var key in obj){
        if (typeof(obj[key]) !== 'Object')
            outcome = comparer(101, obj[key]);
        else
            outcome = retrieveValueFromObject(obj[key],101);
    }
    return outcome;
}

I have not had the chance to test this myself.

Answer №3

To efficiently extract all values from an object and store them in an array, a recursive function can be used along with the Array.prototype.indexOf() method for checking:

function extractValues(obj) {
    var result = [];
    for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
            var curVal = obj[key];
            if (typeof(curVal) === 'object') {
                result = result.concat(extractValues(curVal));
            } else {
                result.push(curVal);
            }
        }
    }
    return result;
}
console.log(extractValues(o));
console.log(extractValues(o).indexOf(101) !== -1);
console.log(extractValues(o).indexOf('nosuchvalue') !== -1);

Playground

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

Increasing the date field value in Mongoose, ExpressJS, and AngularJS with additional days

I encountered an issue while attempting to extend the number of days for an existing Date field in mongoose. Despite no errors being displayed in the browser or console, something seems to be amiss. Can anyone identify the problem in this code snippet? ...

Can a JavaScript (NodeJS) command or function be executed without halting the program in case of an error?

Is there a way in JavaScript to execute a function without interrupting the program if an error occurs? player.play('./sounds/throughQueue.mp3', function(err){ // let the program continue execution even if ther ...

Removing a SubDocument from an Array in Mongoose

For my project, I am utilizing mongoose to create a database. The schema for my Class looks like this: const mongoose = require('mongoose') const classSchema = mongoose.Schema({ _id: mongoose.Schema.Types.ObjectId, consultant: { type: mo ...

Exploring Angular JS: Understanding the Framework's Structure and FAQs

After diving into the world of AngularJS and familiarizing myself with its tutorial and documentation, I find myself in need of guidance on organizing the structure of my project. My goal is to create a single page app with different main sections such as ...

Tips for retrieving data from functions that make HTTP requests in node.js?

Calling the getStockValue() function from another JavaScript file looks like this: var stock=require("./stockdata"); var data = stock.getStockValue()); The data variable currently only contains "-BEGIN-". My goal is to retrieve the body object returned ...

Utilizing the power of HTML5 canvas technology, coupled with advanced

We are currently experimenting with using HTML5 canvas in conjunction with tablet styluses. However, we have encountered an issue where palm touching on multitouch tablets causes unintended lines to appear while drawing. Is there a way to disable multitou ...

Using double parentheses in JavaScript

Although I am not a JS/Front-end developer, I currently need to dive into one of React.JS UI libraries. During my exploration, I stumbled upon something that seems unusual to me. return /*#__PURE__*/(0, _jsxRuntime.jsxs)(TextFieldRoot, (0, _extends2.defaul ...

No need to conceal content when switching to another tab if the tab is set to stay in place

My current setup involves using material UI and react-sticky, which has been functioning well. However, I have encountered an issue that I am seeking help with. Here is a link to what I have tried so far. Below are the steps to reproduce this issue: S ...

Is there an issue with passing data from middleware to controller in restify when using req.data?

exploring the project demo structure middleware auth.js routes user.js controllers userController.js auth.js exports.authUser=(req,res,next)=>{ ... //received user value successfully req.user=user; return next(); } user.js (route) server.g ...

How to use jQuery to target elements by class and find a particular value

Here's a scenario that I have: <ul> <li class="somename">1</li> <li class="somename">2</li> <li class="somename">3</li> <li class="somename">1</li> </ul> Now, let's say I have ...

Would you like to learn how to extract data from a specific textbox using jQuery and save it to a variable when the textbox is in

Below is a textbox that I am working on: <input type="text" name="company" id="company" required /> I am trying to figure out how to use jQuery to capture the values inside the textbox whenever they are typed or selected. Despite my efforts, I hav ...

Using JQuery mobile to switch pages with a swipe gesture

I am struggling to understand why I can't change pages in my JQuery mobile document when I swipe right. The swipe event is written correctly because when I test it with alert("test"); it works fine. This is the code I've used: <script> $( ...

Continuously decrease a sequence of identical numbers in an array through recursion

One of the key challenges was to condense an array of numbers (with consecutive duplicates) by combining neighboring duplicates: const sumClones = (numbers) => { if (Array.isArray(numbers)) { return numbers.reduce((acc, elem, i, arr) => { if ( ...

How can I redirect to a different page with a keypress event in Next.js?

I am looking to implement a redirection function in nextjs when users press a key. There is a search input field where users can type and then hit the enter key to navigate to another page. Here's what I have attempted: const handleKeyPress = (e) = ...

Creating a customized post method in Angular's resource API

I am looking to streamline my code for posting data to a SharePoint list by utilizing a resource factory. Currently, I have been posting data using the following method: this.save = function(data) { data["__metadata"] = { "type": getItemTypeForListNam ...

Shifting an item to a specific location using three.js

I'm attempting to fire bullets or projectiles utilizing three.js: let renderer, camera, scene, light, plane, cube, spheres; initialize(); animate(); function initialize() { renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true }); ...

"Angular JS: Troubleshooting the Issue of Default Selection Not

Struggling to set a default selected option in my dropdown, but no matter what I try, it just won't work. The output that keeps getting generated is like this: Output: <select ng-init="selectedFrom = phoneNumbers[0]" ng-options="phone.Number for ...

Step-by-step guide on generating a deb or exe file for an Angular Electron application

I am currently developing an Angular 6 project and I have a desire to turn it into a desktop application using Electron. After successfully installing Electron in my project, I encountered some challenges when trying to create builds for multiple platforms ...

Attempting to comprehend the reason behind the presence of additional parentheses at the conclusion of a function invocation

Just a quick question I have while experimenting with an example involving OAuth. I want to make sure I fully understand what's going on before incorporating it into my own code. The example uses node, express, and passport-azure-ad. In the code sni ...

Issue with Jquery .scroll() not functioning in Internet Explorer when using both $(window) and $(document). Possible problem with window.pageYOffset?

Here is the code snippet I am currently struggling with: $(window).scroll(function() { var y_scroll_pos = window.pageYOffset; var scroll_pos_test = 200; if(y_scroll_pos > scroll_pos_test) { $('.extratext').slideDown(&a ...