Exploring ways to loop through values within nested objects

const schoolArr = {
  class10: { 
           studentInfo: {name: 'John'}, 
           exam: {result: 'pass'} 
           },
  class11: { 
           studentInfo: {name: 'Alis'}, 
           exam: {result: 'pass'} 
           },
  class12: { 
           studentInfo: {name: 'Nick'}, 
           exam: {result: 'fail'} 
           }
};

Looking for a solution to generate a list of student names if the exam result is 'pass'. The classes (class10, class11, class12) are dynamically changing and I'm struggling with how to iterate through these dynamic values.

The desired output should be an array like this: student = ['John', 'Alis']

Answer №1

Here is the solution for restructuring the updated object:

  1. First, filter out the object values.
  2. Next, map to extract the names of students.

Keep in mind: It is possible to destructure objects at multiple levels.

Another important point: Avoid using the same key multiple times in an object as it will overwrite the previous entry with that key, which can lead to unexpected behavior.

const schoolArr = {
  class10: {
    studentInfo: { name: 'John' },
    exam: { result: 'pass' }
  },
  class11: {
    studentInfo: { name: 'Alis' },
    exam: { result: 'pass' }
  },
  class12: {
    studentInfo: { name: 'Nick' },
    exam: { result: 'fail' }
  }
};

console.log(
  Object.values(schoolArr)
    .filter(({ exam: { result } }) => result === 'pass')
    .map(({ studentInfo: { name } }) => name)
);

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

Extra Pathway

Having trouble adding a second route to the /privacy page. The error "Cannot GET /privacy.html" keeps popping up. Any suggestions? This code seems to be failing to display the privacy.html content app.get('/privacy', function(req, res) { res.s ...

No response received from Node server following successful data insertion into MongoDB

I recently tried to insert data into MongoDB using Node.js, but unfortunately I am not receiving the expected response from the server. Instead of getting a message like Data has been saved, I encountered some errors. Below is the code snippet I used: con ...

Issue with setTimeout Function in Google App Script

I am working with a standard Google App Html form that collects data and stores it in a spreadsheet. Below are the details of the files: HTML Form: <!DOCTYPE html> <html> <head> <base target="_top"> <?!= include("c ...

Prevent the user from being redirected to the login page again after they have already logged in, even if they attempt to go back using the browser's back button

I am in the process of building a login page that checks certain conditions and redirects the user to the home page. However, I want to implement a feature where once the user has visited the home page, they cannot go back to the login page by clicking the ...

Having difficulty extracting image and product names from Amazon or Flipkart pages using Jsoup

I'm having trouble retrieving the main image and product name from Amazon or Flipkart using Jsoup. This is my Java/Jsoup code: // For amazon Connection connection = Jsoup.connect(url).timeout(5000).maxBodySize(1024*1024*10); Document doc = connectio ...

Start by declaring a scope variable using AngularJS

My go-to method for retrieving data from the server and displaying it on various components like tables or charts is by using ng-init="controllerFunction()". This function needs to be called every time the page loads. While ng-init gets the job done, I ca ...

When you encounter a situation where defining a callback is not feasible while using AngularJS JSON

My goal is to utilize Angularjs for retrieving data from the USGS Earthquake feed. Unlike other APIs where adding ?callback=JSON_CALLBACK at the end of the URL allows Angular to process the data, the USGS feed does not support this option. The URL I' ...

Is there a way to efficiently add delimiters to an array using jquery dynamically?

Just joined this community and still figuring things out. I have a question - how can I use jQuery to dynamically add a delimiter like "|" after every 3 elements in an array? This way, I can explode the array and utilize the resulting arrays separately. He ...

Get the whole webpage content (HTML, images, JS) using Selenium with Python

Is there a way to fully download the source code of a dynamically generated website like www.humkinar.pk in simple HTML form? I've attempted using the driver.page_source function from selenium, but it doesn't seem to capture everything, leaving o ...

Does it make sense to start incorporating signals in Angular?

The upcoming release, as outlined in RFC3, will introduce signal-based components with change detection strategy solely based on signals. Given the current zone-based change detection strategy, is there any advantage to using signals instead of the tradi ...

In order for element.click() to be successful, alert() must be called beforehand

Recently, I created a tampermokey script that keeps track of the i intervals and automatically clicks on the next video. However, it's quite strange that the script only works properly when the alert line is uncommented: var i = 1; setInterval(functi ...

Guide on displaying an element depending on the chosen value from a dropdown list using AngularJS

Below is the HTML code I am working on: <select ng-model='selectedtype' ng-options='item.tagname for item in types.name'> <option value="">select type</option> </select> <p ng-show = 'selectedtype.t ...

Unable to change the text with Jquery functionality

I currently have an iframe code that contains the word [UID]. My goal is to replace this word with a different word of my choosing. <iframe class="ofrss" src="https://wall.superrewards.com/super/offers?h=asacgrgerger&uid=[UID]" frameborder="0" widt ...

Angular CDK Overlay allows for bringing multiple overlays to the front effectively

Currently, I am experiencing an issue with Angular 15 where a click event placed within a mousedown event does not trigger. Interestingly, if the position of the element is not changed using appendChild, both the mousedown and click events work as expected ...

Google Chrome's Handling of Mouse Up and Down Events

My HTML5/CSS setup is pretty straightforward: HTML <canvas id="canvas" width="500" height="500" ></canvas> JS var canvas = $("#canvas"), ctx = canvas[0].getContext("2d"); ctx.fillStyle = "gray"; ctx.fillRect(0, 0, 500, 500); $(docume ...

Determine the total number of arrays present in the JSON data

I'm currently working on a straightforward AngularJS project, and here's the code I have so far: This is my view: <tr ng-repeat="metering in meterings"> <td>1</td> <td>{{metering.d.SerialNumber}}</td> ...

Managing server errors when utilizing Observables

i am currently developing an Angular 2 application and part of it includes a login feature that utilizes this service. import { Http, Response } from '@angular/http'; import {Injectable} from '@angular/core'; import 'rxjs/add/op ...

Remove all input fields within an HTML file using a TypeScript method implemented in an Angular 2 component

Within my Angular project, there are several input elements in the HTML file that are not enclosed within a form tag. I am looking to create a function in the TypeScript file that will clear all of these inputs. I attempted to utilize ViewChild, but it a ...

What is the best way to upload mp3 files using Angular?

Hello, I am a beginner with Angular and I could use some guidance. I am looking to upload mp3 files from my Angular application and then send them to the backend to be saved in my local database. Any tips or suggestions on how I can achieve this would be ...

Different ways to streamline the validation process for multiple input fields in a form using Vue 3

Within my application, there lies a form consisting of numerous input fields. These text input fields are displayed based on the selection made via radio buttons. I am currently validating these input fields by specifying the field name and its correspondi ...