What is the process for sending a paired key value to all properties with the same name?

I have a JSON data structure that looks like this:

{
      "prerequisites": [
        "Modeling",
        "Dynamics",
        "Statics"
      ],
      "targets": [
        "Aerospace students",
        "Mechanical students",
        "Civil engineering students",
        "Marine engineering students"
      ],
      "sections": [
        {
          "title": "How to install Abaqus.",
          "achievements": [
            "How to turn on the computer",
            "How to install Abaqus",
            "How to open Abaqus."
          ],
          "lectures": [
                {
                    "title": "Tutorial for starting Windows",
                    "media": "PDF file address or video link"
                },
                {
                    "title": "Tutorial for starting Windows",
                    "media": "PDF file address or video link"
                }
            ]
        }
      ]
}

In TypeScript (Angular 5), I want to add a pair of key, value {"unlock_users": 0} to all elements in the lectures array within each section. How can I achieve this?

I attempted to loop through the sections and lectures using the following code snippet in an attempt to find the index and push the key, value pair by index, but it returned undefined. Here is the code:

for (const {section, index_s} of this.data['sections'].map((item, index) => ({ item, index }))) {
  console.log(section);
  console.log(index_s);
   for (const {lecture, index_l} of section['lectures'].map((item, index) => ({ item, index }))) {
     console.log(lecture);
     this.data['sections'][index_s]['lectures'][index_l]['unlock_users'] = 0;
   }
}

Answer №1

To achieve this, utilize the Array.prototype.map method as demonstrated below:

let data = `{
      "categories": [
        "Modeling",
        "Dynamics",
        "Statics"
      ],
      "audience": [
        "Aerospace Engineering Students",
        "Mechanical Engineering Students",
        "Civil Engineering Students",
        "Marine Engineering Students"
      ],
      "modules": [
        {
          "title": "How to Install Abaqus Software.",
          "steps": [
            "Switch on the computer",
            "Install Abaqus Software",
            "Open Abaqus Software"
          ],
          "lessons": [
                {
                    "title": "Windows Start-Up Tutorial",
                    "media": "PDF file link or video"
                },
                {
                    "title": "Windows Start-Up Tutorial",
                    "media": "PDF file link or video"
                }
            ]
        }  
      ]
}`;
let object = JSON.parse(data);
object.modules = object.modules.map(obj => {
  obj.lessons = obj.lessons.map(lesson => {
    lesson.unlock_users = 0;
    return lesson;
  });
  return obj
});
console.log(object.modules);

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

An error occurred: Unable to access the 'indexOf' property of an undefined variable within the angularjs framework

Hello world of coding, I am a newbie seeking help from experts. The angularJs error I've encountered in the file has been identified and is related to this code snippet: if( searchItemsSmallLetters.indexOf(searchTextSmallLetters) !== -1){ Your assi ...

What steps should I take to rearrange the tab order of two elements located in the middle of the page?

I have a dynamic web page and I am looking for a way to reorder the tab order of two elements within the content without having to set the tab index for every preceding element. Is there a way to assign a tab index relative to an element's position in ...

What is the process for creating a sense of distance within a sphere using three.js?

I have a three.js sphere with a textured interior and the camera positioned at the center of it. My goal is to make the texture appear much farther away than it currently does. I attempted to incrementally increase the radius from 4,000 to 180,000, making ...

Combining Arrays Together in TypeScript

I am in need of a solution to merge two arrays into one using TypeScript. First Array Object: export interface Item{ Label : string, Code : string, Price : number, } Second Array Object: export interface Amou ...

Having trouble retrieving data from the database when passing input to a mongoose query using an href tag in Node.js

Welcome to My Schema const AutomationSchema=new mongoose.Schema( {EventName:String, EventDate:String, EventLocation:String, EventDetails:String } ) The Events Model const EventsModel=new mongoose.model("Events",AutomationSchema ...

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 ...

Crockford's system for safeguarded entities

Despite the abundance of questions and resources related to "Javascript: The Good Parts," I am struggling to comprehend a specific sentence in the book. On pages 41-42, the author defines the serial_maker function as follows: var serial_maker = function ( ...

Looking for assistance with designing a responsive login box

Greetings! I'm a beginner in programming, so please excuse me if my issue seems simple. I have a website with a login form, but I am struggling to make it responsive. Every time I attempt to do so, the entire layout gets messed up. Could someone kin ...

Is there a way to switch colors with the click of a button?

I'm looking to incorporate a bootstrap color picker into my website. I want the button inside this div to trigger the color chart and change the background color of the entire div when clicked. Can anyone help me achieve this functionality? <d ...

What are the implications of adding custom attributes to HTML elements?

Similar Questions: Custom attributes - Good or Bad? Non-Standard Attributes on HTML Tags. What are Your Thoughts? While working on a current learning project, I encountered the need to add an attribute that would store a numerical value. Initially ...

Tips for disabling automatic browser scrolling to a specific div ID?

I have a webpage with a vertical accordion in the center to display content. Upon loading the page, the accordion is centered. However, when a user clicks on a tab, the entire page scrolls up, moving the tab to the top of the browser. Is there a way to pre ...

Exploring the integration of angular-ui-select into an angular seed project

I set up a new project using the starter template from https://github.com/angular/angular-seed and now I'm attempting to integrate angular-ui-select for dropdown menus. I've added select.js and select.css files to my index.html as well as install ...

Subscribing and updating simultaneously will not function. Whichever action is attempted, the other will result in an error, and the

import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; import {AngularFireDatabase, AngularFireObject} from 'angularfire2/database'; import{ShoppingItem} ...

When using Vuetify's v-text-field with the type "number", remember to assign a null value instead of an empty string

One issue I've encountered is that when using v-text-field with the type="number" attribute, the value is set to an empty string after manual clearing. Ideally, I would like it to return null in such instances. Is there a way to set an attr ...

Add and condense sub-row

I am struggling to make the child row collapse and append when clicking on the parent row. It seems like my code is not working properly. Can anyone offer some guidance or assistance? This is the code for the parent row: $j(document).ready(function(){ $ ...

Is it necessary to utilize RequestHandler every time I create an Endpoint in Sveltekit?

As I work on creating a Todo website, I came across a video tutorial about building a Svelte fullstack app. The teacher in the video demonstrated the use of RequestHandler to create an endpoint. However, in the SvelteKit documentation, it recommends using ...

Guide on Implementing a New Method into a React Functional Component

I have a component that looks like this: const Abc: React.FC<AbcTypes> = ({...}) => {...} Abc.getLayout = () => {...} I am not sure how to properly define or extend the method getLayout on the Abc component in TypeScript? ...

Incorporating AngularJs into an iframe

Can someone please help me troubleshoot why this jsfiddle link is not functioning properly? Specifically, I am encountering issues with retrieving the value of videoId. Interestingly, when I eliminate ngRoute from the module, everything works as expected ...

Neglecting asynchronous Ajax functions once they have been called

I currently have a function that looks like this: $("#transfer").click(function(){ var token_rec = $("#token_rec").val(); var user_rec = $("#user_rec").val(); var subdomain_rec = $("#subdominio_rec").val(); var req_rec ...

Extract tag from XML by converting from PHP to JavaScript

I have a server-side script that I need to convert to client-side using JavaScript. However, I'm not very familiar with JS, so any assistance would be greatly appreciated. PHP code snippet: function getAlexaRank($theUrl) { $alexa_url = "http://d ...