Tips for inserting or updating inner objects within a JavaScript array

On my hands, I hold a JavaScript array structured like this:


        const Rooms = [{
            name:"Science",
            students:[
                {user:"Tom",emotion:"Happy"},
                {user:"Marry",emotion:"Angry"},
                {user:"Adam",emotion:"Happy"}
            ]
        },{
            name:"Maths",
            students:[
                {user:"Stewie",emotion:"Angry"},
                {user:"Cleavland",emotion:"Angry"},
                {user:"Meg",emotion:"Happy"},
                {user:"Peter",emotion:"Angry"},
                {user:"Chris",emotion:"Happy"}
            ]
        },{
            name:"History",
            students:[
                {user:"Monica",emotion:"Angry"},
                {user:"Chandler",emotion:"Happy"},
                {user:"Joe",emotion:"Happy"},
                {user:"Ross",emotion:"Angry"}
            ]
        }];
    

I am seeking a way to identify a room by its name and modify or insert a student as needed. For instance, I should be able to locate the room named "Maths" and update a student within it. If the student is already listed, only their emotion needs to change.

The following code snippet was my initial attempt, but it failed to replace the existing student:


        Rooms.forEach((e)=>{
            if(e.name === "Science"){
                e.students.push({user:"Tom",emotion:"Surprised"});
            }
        });
    

How can I effectively search for a specific JSON entry and either alter an existing student's details or introduce a new student (in case they are not present)?

Answer №1

Locate and update the student "Tom" in the array:

For example, to find "Tom" and modify their emotion:

Rooms.forEach((e)=>{
  if(e.name === "Science"){
   const tom = e.students.find((student) => student.user === "Tom");
   if (!tom)       
      e.students.push({user:"Tom",emotion:"Surprised"});
   else
      tom.emotion = "Surprised";
  }
});

Tip: Instead of using forEach, you can also utilize find to locate the room:

const e = Rooms.find((room) => room.name === "Science");
if (e) {
  const tom = e.students.find((student) => student.user === "Tom");
  if (!tom)       
     e.students.push({user:"Tom",emotion:"Surprised"});
  else
     tom.emotion = "Surprised";
  }
}

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

How to Extract Minutes in Datatables Timestamps and Apply Custom Styling

Working with Datatables v1.10 Right now, my table is showing a date in the second column in the format 17-04-2019 14:34, which is how it's stored in the database. The filtering and searching functionality are all working as expected. The current HTM ...

Learn how to utilize JavaScript in VB.NET ASP.NET to successfully close a web form

In the scenario, when the session expires in our system or application, it automatically redirects to the log-in page. If I have the application open in two different browsers and the session times out in one browser window, ideally it should also close t ...

Limiting the zoom in three.js to prevent object distortion caused by the camera

I'm currently in the process of developing a three.js application where I have successfully loaded my STL objects and incorporated 'OrbitControls'. However, I am encountering an issue when attempting to zoom using the middle scroll button on ...

Ways to retrieve a list of elements from a string using SQL

I need assistance in splitting the itemid into a list to use as a condition in another query: data --------------------------------------------------- [{"shopid":64522541,"itemid":1260324852},{"shopid":31863766,"itemid":1265550228}] I attempted to use JS ...

"Node.js seems to be returning an empty array instead of the expected

Database Information var mongoose = require('mongoose'); var DataSchema = mongoose.Schema({ name:{ type: String, required: true }, create_date:{ type: Date, default: Date.now } }); var Data = mo ...

My Special Character is not encoded by JSON

Within my database table, there are two fields present: Title = Testing Title Description = CREDITO FISCAL OCDE CFDI AMPAROS REVISIÓN ELECTRÓNICA REGLAMENTO ISR RIF ID: 44 However, when I receive the json response, it always returns with a null descrip ...

Add opening and closing HTML tags to enclose an already existing HTML structure

Is there a way to dynamically wrap the p tag inside a div with the class .description-wrapper using JavaScript or jQuery? This is the current html structure: <div class="coursePrerequisites"> <p> Lorem ipsum.. </p> </ ...

How can async/await help in retrieving the value of a CORS request?

Trying to make a CORS request and utilize async/await to extract the value from it (using jquery). The functions createCORSRequest and executeCORSRequest seem to be functioning correctly, so the implementation details are not my main concern. The function ...

Choosing multiple options from a list

I am working on a messaging app where users can compose and send messages to contacts. Currently, I am only able to send messages to one contact at a time. My goal is to enable users to select multiple contacts to create group messages. Since I am new to a ...

Setting the second tab as the primary active tab

I am currently working on a script that is well-known, and everything is functioning perfectly. However, I want to change it so that when the page is first opened, it displays the second tab instead of the first one (the first tab being a mail compose tab ...

An error popped up as I attempted to load an existing design within the vue-email-editor

https://i.stack.imgur.com/0ObU5.png Check out the code snippet below for the function I have created: editorLoaded() { this.$refs.emailEditor.editor.loadDesign(this.emailJson); console.log('editorLoaded'); }, ...

What are some methods to maintain consistent height for each list item in an unordered list on small screens like mobile devices?

While vh works well for larger screen sizes such as laptops, it may not maintain the height of the li on smaller devices like mobiles. Is there a better approach than relying on media queries to achieve responsiveness across different screen sizes? ...

encountering difficulties when trying to install npm packages in node.js

Starting out with Node.js and new to installing packages like express.js and underscore.js using NPM. However, every time I attempt to install using the following commands: npm install express, npm install underscore I keep encountering errors. Please ...

Tips for resolving flickering animations in CSS and JavaScript

Is it possible to dynamically set a scale and margin for an element in order to center it fluidly using the wheel event? I am aiming to achieve a smooth transition while also adjusting scroll position on the wrapping element in a fluid manner. In the prov ...

Could you identify the unique patterns present in this specific Backbone TodoMVC demonstration?

Exploring the todomvc backbone codes example, focusing on the structure within the js/ directory: ├── app.js ├── collections │   └── todos.js ├── models │   └── todo.js ├── routers │   └── router.js ...

JavaScript - Dynamically loaded CSS: CSS variables are not immediately accessible to JavaScript, but are successfully evaluated within the CSS itself

I am encountering an issue with dynamically loading stylesheets via JavaScript into my application. Within these stylesheets, I have various CSS variables that I need to access and modify from my JavaScript code. When the stylesheets are directly embedded ...

Utilizing R for Web Scraping: Extracting Data from a Form with a POST Method and

Currently, I am attempting to extract data from a website using the API which can be observed being called in the Safari Network Tab. However, it seems like the API is not properly receiving the form parameters when passed as JSON or throws an error if at ...

Extract JSON data from Python API

Currently, I am delving into web programming and have created a Python API that queries an SQL database to return a JSON. The functionality of the API is as expected. In parallel, I've developed a controller where I execute a GET request to utilize t ...

Choose a particular character in a text that corresponds with a regular expression in Javascript

I am looking to replace the symbols < and > within the text. I have constructed a regular expression as follows: (<span[^>]+class\s*=\s*("|')subValue\2[^>]*>)[^<]*(<\/span>)|(<br(\/*)>) This ...

Troubleshooting Typescript app compilation problem in a Docker environment

I am encountering a challenge while trying to build my typescript Express app using Docker. Surprisingly, the build works perfectly fine outside of Docker! Below is the content of my Dockerfile: FROM node:14-slim WORKDIR /app COPY package.json ./ COPY yarn ...