Exploring deep layers of nested arrays within a JSON structure

Calculate the sum of ages for dogs in a given dataset and convert them to dog years.

mL/hr

I am looking for the optimal method to access array elements within a JavaScript object. For example, I want to retrieve the first faculty name and specialization for each course.

var students = 
{  
   deptartment:[  
      {  
         name:'Computer Science',
         age:20,
         Course:[  
            {  id: 100000
               name:'Object Oriented Programming',
               faculty:[  
                  {  
                     id:123,
                     name:'John',
                     Specialization: [
                       {name: 'science'},
                       {name: 'Physics'}
                     ]
                  }
                ]
            },
            {  id: 100001
               name:'C#',
               faculty:[    
                 {  
                     id:124,
                     name:'Denis', 
                     Specialization: [
                       {name: 'Ecnonomics'},
                       {name: 'Physics'}
                     ]
                  }
               ]
            }
         ],

      }
    ]
};

To get the faculty name and specialization, you can use the following code:

  var courses= deptartment && deptartment.Course ;
    var facultyWithSpecialization= {};
    if(courses){
      courses.forEach(course =>{
        var fname = course.faculty && course.faculty[0].name;
        var s= course.faculty && course.faculty.Specialization;
        facultyWithSpecialization[fname] = s && s[0].name;
      })
    }

Instead of department.Course, consider using Object.assign({}, department.Course).

An attempt was made with the following code but it did not yield significant results.

 var courses=Object.values(Object.assign({}, deptartment.Course));
var fname = Object.values(Object.assign({}, course.faculty[0].Specialization[0]));

Expected output:

'John': 'science'
'Denis': 'Ecnonomics'

Answer №1

Feel free to give this a shot. The object had numerous errors, such as spelling mistakes and formatting issues

var students = {
  department: [{
    name: 'Computer Science',
    age: 20,
    Course: [{
      id: 100000,
      name: 'Object Oriented Programming',
      faculty: [{
          id: 123,
          name: 'John',
          Specialization: [{
              name: 'Science'
            },
            {
              name: 'Physics'
            }
          ]
        },
        {
          id: 124,
          name: 'Denis',
          Specialization: [{
              name: 'Economics'
            },
            {
              name: 'Physics'
            }
          ]
        }
      ]
    }],

  }]
}
var obj = {};
students.department.forEach((e) => {
  e.Course.forEach((k) => {
    k.faculty.forEach((l) => {
      obj[l.name] = l.Specialization[0].name
    })
  })
})
console.log(obj)

Answer №2

It appears that there was a typo with deptartment, it should be corrected to department. I made some adjustments to your JSON code to fix a few bugs:

var students = {  
   departments:[  
      {  
         name:'Computer Science',
         age:20,
         Courses:[  
            {  id: 100000,
               name:'Object Oriented Programming',
               faculty:[  
                  {  
                     id:123,
                     name:'John',
                     Specialization: [
                       {name: 'science'},
                       {name: 'Physics'}
                     ]
                  },
                 {  
                     id:124,
                     name:'Denis', 
                     Specialization: [
                       {name: 'Ecnonomics'},
                       {name: 'Physics'}
                     ]
                  }
               ]
            }
         ],
      }]
}

To achieve the desired nesting, you can utilize the map method:

students.departments.map(
  department => department.Courses.map(
    course => course.faculty.map(
      student => ({
        name: student.name,
        specialization: student.Specialization[0].name // Remember to handle null values!
      })
    )
  )
)

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

The .load() function seems to have a problem with my slider widget

I am facing an issue with a slider on my page that displays posts from a specific category. When the user clicks on "next category", the content slides to the left and new content is loaded along with its respective slider. The problem arises when the loa ...

Retrieving a specific field from an object within an array

Struggling with Meteor and MongoDB, I am having trouble accessing a specific field from objects within an object array. Details of my documents: { "_id" : "p6c4cSTb3cHWaJqpG", "createdAt" : ISODate("2016-05-11T11:30:11.820Z"), "username" ...

A Vue.js component modifies one store state variable but leaves another unchanged

Currently developing a Vue 3 application that utilizes Vuex and the Composition API. Encountered an issue while working on it. A component is supposed to display elements based on the state of two store variables. One is an array, and the other is a bool ...

Filtering the inner ng-repeat based on the variable of the outer ng-repeat

I have a collection of elements. Some of these elements are considered "children" of other elements known as "parent" elements. Instead of rearranging the JSON data received from the server, I am attempting to filter the results within the ng-repeat loop. ...

What is the process for AngularJS to automatically populate the initial tag value in an SVG template?

I'm currently working on an AngularJS directive that needs to update different attributes within an svg tag. angular.module("complexNumbers") .directive("cartesianPlane", function() { return { restrict: "E", scope: { }, templateUrl: " ...

What is the best way to pass a model bound to a view from an ajax request triggered by clicking a button to a controller

Below is the code snippet for my AJAX call: $('#addNominationForm').on("submit", function (e) { debugger; e.preventDefault(); $.ajax({ type: 'post', url: '@Url.Action("AddNominat ...

Exploring the world of Leaflet. Have you ever encountered situations where adding a variable name to the GeoJSON file is crucial

Currently, I am in the process of learning Leaflet, JavaScript, and more. To test my understanding, I am using code examples from the Leaflet website and making modifications for my own purposes. However, I have noticed that in all the examples I have co ...

Array of dynamically typed objects in Typescript

Hello, I am a newbie to Typescript and I recently encountered an issue that has left me stumped. The problem I am facing involves feeding data to a Dygraph chart which requires data in the format [Date, number, number,...]. However, the API I am using prov ...

What sets apart map and collect in Ruby?

I have searched online and found conflicting opinions - is there a distinction between using map and collect on an array in Ruby/Rails? Although the documentation does not indicate any differences, could there be variations in functionality or efficiency? ...

What is causing this issue that is preventing me from async rendering Vue components?

I am new to working with Vue and I am attempting to lazy load a Component. However, I encountered an error that seems to be related to a syntax issue. Below is the code snippet: <template> <div class="container"> <h1>Asy ...

Searching for the "MongoDB" object using Node.js to execute an array query

[ { "_id" : ObjectId("5abce64d86d3289de052a639"), "username" : "doggy", "email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2a4e454d4d536a594b484b4449435f44435c044f4e5f">[email protecte ...

Tips for importing a PDF file and storing it in your database

I have a project using Angular 7, .NET Framework, and MongoDB where I am creating user profiles. One of the requirements is to allow users to optionally upload a PDF file along with their other information. This is what I have implemented so far: <labe ...

Experiencing difficulties in retrieving property of a non-object when working with json and php

My current project involves using AngularJS to collect user input from a form, then sending this data to a PHP backend for processing. After decoding the JSON file in PHP, I then perform a database lookup to find information that matches the input values. ...

What is the best way to convert all the values from a dropdown list into Million or Billion using JavaScript?

Is there a way to convert the output numbers on the dropdown generated by this code into abbreviated formats, like in the examples below? (Example 1: If the output number is 1000000, I want it to show as 1M (million). Example 2: If the output number is 100 ...

Generating option list from API JSON responses

I am currently developing a news app using React. I have set up my API to fetch data from newsapi.org and my goal is to display the available news source options in a dropdown list within my select component. However, instead of listing all news sources w ...

Retrieve the text input from the text field and display it as

Is there a way to display what users enter in a textfield when their accounts are not "Activated"? Here's an example: if(active == NULL);{ //I've attempted the following methods. //In this scenario, 'username' is the name of ...

Determine if the content has finished loading once it has been added using JavaScript

I am currently working on a project in pure JavaScript that involves implementing a feature similar to Facebook's message loading. This means that when you scroll to the end of the page, new HTML content is loaded and added to the page. The additional ...

The Google Books API has reached its limit for requests

Encountering a rate limit exceeded error from the Google Books API while using this demo: To reproduce, open the developer console in Chrome and perform some searches. The rate limit errors will be displayed in the console. [],"lazyUpdate":null},"status" ...

In Java, parsing JSON succeeds for numbers but fails for strings

My current task involves developing a parser to handle incoming JSON data that has unpredictable value structures. For instance, a key in the parent JSON can contain an integer, a string, or even another JSON string. While working with the JSON.parse() met ...

Strip away all HTML attributes within a string

I am in the process of developing an internal tool that allows a designer to input exported svg code into a text area and have the html code displayed in a syntax highlighter () When they paste their code like this <svg xmlns="http://www.w3.org/20 ...