What is the best way to access and modify a nested object within a complex object containing an array of objects?

I've got the course structure all sorted out, but I'm struggling to understand how to retrieve a lesson object by its ID and also update a lesson object with new property values.

If anyone could provide some guidance on the right approach, it would be greatly appreciated.

{
   id: 1,
   name: 'A Fantastic Course',
   description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla porttitor lorem vel turpis congue euismod.',
   sections: [
      {
         id: 1,
         sort_order: 1,
         name: 'Section one',
         lessons: [
            {
               id: 1,
               sort_order: 1,
               name: 'Lesson One'
            },
            {
               id: 3,
               sort_order: 2,
               name: 'Lesson Three'
            },
            {
               id: 2,
               sort_order: 3,
               name: 'Lesson Two'
            }
         ]

      },
      {
         id: 2,
         sort_order: 2,
         name: 'Section Two',
         lessons: [
            {
               id: 4,
               sort_order: 1,
               name: 'Lesson Four'
            },
            {
               id: 5,
               sort_order: 2,
               name: 'Lesson Five'
            },
            {
               id: 6,
               sort_order: 3,
               name: 'Lesson Six'
            }
         ]
      }
   ]
}

Answer №1

const obj = {
   id: 1,
   name: 'An Incredible Class',
   description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed et justo odio.',
   sections: [
      {
         id: 1,
         sort_order: 1,
         name: 'First Section',
         lessons: [
            {
               id: 1,
               sort_order: 1,
               name: 'Lesson A'
            },
            {
               id: 3,
               sort_order: 2,
               name: 'Lesson C'
            },
            {
               id: 2,
               sort_order: 3,
               name: 'Lesson B'
            }
         ]

      },
      {
         id: 2,
         sort_order: 2,
         name: 'Second Section',
         lessons: [
            {
               id: 4,
               sort_order: 1,
               name: 'Lesson D'
            },
            {
               id: 5,
               sort_order: 2,
               name: 'Lesson E'
            },
            {
               id: 6,
               sort_order: 3,
               name: 'Lesson F'
            }
         ]
      }
   ]
}

const lessons = [].concat.apply([], Object.values(obj.sections).map(section => section.lessons))

const id = //pick one

const selected = lessons.find(lesson => lesson.id === id)

You may want to experiment with a method like this to flatten the object and store the course and section IDs along with each lesson for easy access.

[].concat.apply([], Object.values(obj.sections).map(section => 
  section.lessons.map(lesson => ({
    ...lesson,
    courseId: obj.id,
    sectionId: section.id
  }))
))

Answer №2

Here is a simple function to find a lesson by its ID.


function searchLessonById(id){
    let result;
    const lessonValues = Object.values(lessons);

    lessonValues.filter(x => Array.isArray(x) ? x.forEach(y => y.lessons.find(z => z.id == id ? result = z.name : null)) : null);
    
    return result;
}

console.log(searchLessonById(3));

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

"RecognitionAudio variable missing" and "InactiveRpcError occurred" [Utilizing the Google text-to-speech API]

I have a goal I'd like to achieve. A user communicates with a web browser. The web browser records the user's voice as a WAV file using Recorder.js and sends it to a server running on Google App Engine Standard environment with Python 3.7. The ...

The ng-model in Angular is unable to capture the initial input value on load

I am currently using a window onload script to obtain longitude and latitude data and pass them to hidden input values. $(function() { window.onload = getLocation; var geo = navigator.geolocation; function getLocation() { if (geo) { geo ...

Working with AngularJS: Accessing a JSON file from the local directory

The answers to my previous questions on this topic have not been satisfactory. It seems that most examples and tutorials for AngularJS online always define tiny JSON arrays directly inside the JavaScript code... So, let's simplify things with a basi ...

Is it possible to execute a function defined within an eval() function using setInterval()?

const evaluation = eval(document.getElementById("codearea").value); setInterval(evaluation, 10); I am seeking a way to access a function that is declared within the eval function, for example: setInterval(evaluation.examplefunc, 10) I attempted ...

Trouble with NodeJS NPM

I'm encountering difficulty when trying to install npm packages. npm ERR! Windows_NT 6.3.9600 npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules&bso ...

Tips for resizing an image to perfectly fit on a compact HTML5 canvas without sacrificing its quality

I need assistance with my code. I'm trying to draw an image on the canvas while maintaining its quality. const canvas = document.getElementById("canvas"); const context = canvas.getContext("2d"); canvas.width = 360px; canvas.height = 360px; const img ...

Different conversations are taking place concurrently. How can we determine which one is currently being attended to

In my application, multiple dialogs are open simultaneously, each with its own set of shortcuts. It is important to ensure that these shortcuts work correctly based on the focused dialog. Is there a way to determine which dialog is currently in focus? Ed ...

Is it feasible to execute a cross-site request forgery attack on a URL that delivers a JSON object as a response?

I am aware of the potential for a Cross-Site Forgery Attack that can target requests returning arrays by manipulating the Array constructor. For instance, let's say I have a site with a URL: foo.com/getJson that provides the following array: [&apos ...

Interactive feature allowing all embedded YouTube videos on a webpage to play synchronously, with sound disabled, and on a continuous loop

I am in the process of developing a button that, when clicked by a user, will trigger all embedded YouTube videos on a specific webpage to start playing simultaneously, with sound muted, and set to loop. The target page for this button implementation can ...

Is it possible to use multiple schemas for one collection name?

I am currently working on creating different schemas for a single collection, such as User or subUser. I aim to store both User and subuser data in the same collection but with different schemas. Here is an example of my schema file: export const AryaSchem ...

Interested in compressing CSS and JavaScript using PHP, but uncertain about the impact on performance and the best methods to implement it?

My current approach involves using PHP to combine multiple css (or js) files into a single file, while also compressing the content using GZIP. For example, the HTML page makes calls to resources like this... <link rel="stylesheet" href="Concat.php?fi ...

Addressing Equity Concerns within JavaScript Programming

I can't figure out why the final line in this code snippet is returning false. Is it not identical to the line above? const Statuses = Object.freeze({ UNKNOWN : 0, OK : 1, ERROR : 2, STOPPED : 3 }); class myStatus extends Object{ co ...

Utilizing the URLSearchParams object for fetching data in React

I've implemented a custom hook named useFetch: const useFetch = (url: string, method = 'get', queryParams: any) => { useEffect(() => { let queryString = url; if (queryParams) { queryString += '?' + queryParam ...

What is causing the ajax code to malfunction?

I am new to ASP MVC and trying to create a login form using AJAX. I have written a JsonResult in the controller to check the username and password, but for some reason it is not working. Here is my controller code: public ActionResult login() { ...

Update the parent element's class style within a targeted div media query

I am facing a challenge where I want the width of my .container element to be 100% when the screen size reaches 900px. The issue is that I have used .container on multiple pages and only wish to change its appearance within the #sub-top div. The terminolo ...

When dynamically adding input fields in Bootstrap, there is a smaller gap between inline inputs

When adding a new list item dynamically in a modal using jQuery append, the spacing in the first li element seems to have a larger gap between the input fields compared to the rest that are added later. Even after checking the developer tools and confirmin ...

What is an effective method for coordinating JQuery animations simultaneously?

My current understanding of $("#someElement").animate() is that it will run asynchronously in relation to other JavaScript statements. For example: $("#anotherElement").css("display", "none"); $("#someElement").animate(); //The CSS display may change a ...

How come I am unable to pass JavaScript values to my PHP5 code?

I'm struggling with this code snippet: <?php $html=file_get_contents('testmaker_html.html'); echo $html; ?> <script type="text/javascript"> document.getElementById('save_finaly_TEST').addEventLis ...

Encountering an issue with a loop in my jQuery function - any solutions?

Having encountered an issue with a select object not working in my form-building function, I resorted to using an ajax call to fetch data from a database table. While the network tab in Chrome shows the data being retrieved successfully, the console displa ...

What strategies can I implement to prevent security alerts in Internet Explorer 8 when accessing Google Maps via a secure connection

When using Google Maps on my project through an https connection, I encountered a problem. Interestingly, the issue only arises in certain browsers while others work fine. Despite searching for a solution extensively, I have not been able to find one. Some ...