Exploring the functionality of the .find() method in JavaScript for accessing nested objects similar to MongoDB's capabilities

While experimenting with JavaScript, I attempted to retrieve an object nested within several other objects using the .find() method. It reminded me of how it can be done in MongoDB, where you can use the '.find()' method along with some hints to achieve similar results. However, my understanding is that the .find() method in JavaScript is primarily meant for arrays. Still, I was curious to see if it could work in the scenario I was testing...

Here is the code snippet:

const arrayLike = {
  length: 1,
  people: {
        person: {
            first name: 'rafa',
            last name: 'rivas',
            age: 20
        },
        person: {
            first name: 'miguel',
            last name: 'blades',
            age: 23
        },
        person: {
            first name: 'mario',
            last name: 'perez',
            age: 93
        },
    }
};
console.log(Array.prototype.find.call(arrayLike, (x) => x ));

After running this code, I found myself puzzled by the unexpected output. Instead of at least returning the array('people') as expected, the console displayed 'undefined'.

Answer №1

function findValue(obj, text) {
let output;
for (let key in obj){
    let firstLevel = obj[key];

    if(firstLevel === text){
        output = obj;
    }else{
        output = 0;
        for (let key2 in firstLevel) {
            let secondLevel = firstLevel[key2];
            
            if(secondLevel === text){
                output = firstLevel;
            }else{
                output = 1;
                for (let key3 in secondLevel){
                    let thirdLevel = secondLevel[key3]
                    console.log(thirdLevel);

                    if(thirdLevel === text){
                        output = secondLevel;
                        console.log(output, ' d')
                    }else{
                        output = 2
                    }
                }
                
            }
        }
    }
}
return output;

}

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

Storing a JavaScript variable in a MySQL database using AJAX and JSP

I'm on a mission to understand ajax and I have my sights set on saving the timeSpentOnPage value from the TimeMe.js library into my MySql database. I've successfully integrated the javascript library into my jsp page, like so: <script type="t ...

Store the input or response from users in local storage using an HTML table

After trying various methods, I have managed to implement a feature where users can input data into an HTML Table and save it using local storage. The goal is to allow users to easily retrieve their saved inputs when they revisit the page. In addition, I ...

Having trouble retrieving data from the json file

Using Ajax to obtain a JSON update: $(document).ready(function(){ $('form').submit(function(event){ event.preventDefault(); var form = JSON.stringify($('form').serializeArray()); $.ajax ({ u ...

Anticipate the moment when a variable will shift

Before proceeding to the next step, I have an observable that must be executed. export class MyExample implements OnInit { flag; constructor(private myService: MyService) { } myFunc() { flag = 0; this.myService.subscribe(data ...

Setting up StrongLoop LoopBack MongoDB datasource for successful deployment on Heroku

Currently, I am utilizing LoopBack version 1.6 and have a local mongoDB server operational for development purposes with the following datasource configuration: "mongodb": { "defaultForType": "mongodb", "connector": "loopback-connector-mongodb", ...

Employ JavaScript regular expressions to extract all the text values from VBA code

Looking to utilize JavaScript regex in order to extract all string values from VBA code. For instance: If cmd = "History Report" Then Range("D2").Formula = "=TEXT(""" & createDate & """,""" & Replace(subtitleFormat, """", """""") & " ...

The position property in CSS does not keep the <script> tag fixed in place

Struggling with keeping a .js validation script in a fixed position on a webpage. Here is the CSS code: div.fixed { position: fixed; bottom: 0; left: 0; } HTML <div class="fixed"> <script src="http://my.gblearn.com/js/javascript.js"></ ...

The Node.js server is failing to retrieve information from the AngularJS application

Having trouble reading data sent from an AngularJS client to the server via $http.post. Can't seem to figure out where I've made a mistake. var data = $.param({ id:$scope.user_id, }); alert(JSON.stringify(data)); $http.post('/getd ...

In my React application, I have integrated p5 sketches that constantly loop and repeat

Currently facing a challenge integrating p5 sketches into my React App. I've tried adjusting the z Index of the toolbar to place the p5 elements underneath, but they end up repeating instead. Check out the repository here (sketches can be found in the ...

Exploring the depths of nested objects in Mongoose using the .populate method

Database Schemas Team.js Schema: var TeamSchema = new Schema({ // Information about a team. name: String, lead: String, students :type: [{ block : Number, status : String, student : { type: Schema.ObjectId, ...

What is the best way to toggle buttons on and off with jQuery?

I've recently started a project for my class, and as a complete beginner in this field, I'm facing some challenges. My server is running on Ubuntu. In script.js, the following code is included: $(document).ready(function(){ $.get('/var/ ...

Identifying Selections Beyond Text Areas and Input Fields

Can jQuery handle selecting content in elements like <div>, or is the select event limited to textarea and input:text only? ...

Exploring the functionality of executeAsyncScript in Selenium

Trying to wrap my head around Selenium's executeAsyncScript documentation found here (https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/JavascriptExecutor.html). In their initial example, they present: long start = System.curr ...

Automatically Populate list upon webpage initialization - React, Redux, Firebase

A webpage I am working on consists of two main components: Categories and Items By utilizing the function initCategories() called within the componentDidMount() lifecycle method of Categories, I successfully display all categories on the screen. The initC ...

jQuery is missing an essential component that is causing an error

I have successfully implemented the following JavaScript code and everything is working fine. However, I'm uncertain if my code is fully correct. I noticed that in my script, I only utilize success: function() without incorporating an error function. ...

The jQuery script that is trying to create a fading effect on an image at intervals is encountering an error message

I am trying to cycle through 4 pictures every 3 seconds while fading them in and out. I have successfully changed the pictures, but when I attempt to use fadeOut, I encounter an error stating "Uncaught TypeError: $(...).fadeOut is not a function" in action ...

How to Customize the ::before Pseudo-element for a mat-expansion-panel-header?

I have a demo where I am attempting to customize the appearance of the mat-expansion-panel-header's ::before pseudo element with the following CSS rules added to styles.scss: mat-expansion-panel-header { position: relative; } mat-expansion-panel-he ...

Performing subtraction on two time values with AM/PM formatting using JavaScript

I'm currently using a date.js plugin to convert my times into date objects and then trying to subtract them. However, the result is not showing as valid. The time format I am working with is 11:00 pm. Here is the code snippet: var tim_i = $('#in ...

What are some alternatives if slowAES isn't functioning properly with CBC/PKCS7?

Is there a way to encrypt data in javascript using CBC/PKCS7 so that it can be decrypted in php or .NET? I've experimented with slowAES, but the encrypted output doesn't seem to be correct. When I compare slowAES and .NET encryption using the s ...

Connecting to another page based on data list selection

I have created a datalist with multiple options and now I want to redirect to another page when one of the options is selected. Here is my initial attempt where I tried to directly add a hyperlink to the option label, but it didn't work as expected. ...