Modifying the value of a property in an object array created using the map method is ineffective

I have a collection of objects: https://i.sstatic.net/XNrcU.png

Within the collection, I wished to include an additional property to the objects.

To achieve this, I utilized the map function:

returnArray = returnArray.map((obj) => {
obj.active = "false"; 
return obj;
});

https://i.sstatic.net/PpiYO.png

At a later stage, I intend to modify the value of the newly added 'active' property to a different value ("true") within a separate function. However, there seems to be an issue with the value not updating.

When attempting to alter the value of a pre-existing property in the original array, the update is successful.

var array = getarrayfunction();
array[index].active = "test";              <-- Not working
array[index].originalProperty = "test";    <-- Works fine

https://i.sstatic.net/HoTIz.png

Could someone shed light on why this is happening and suggest a solution?

Appreciate your help!

Answer №1

To add a new property to an existing object, use the following syntax with quotes ( obj['c'] = "false"). Click here for example

  var petArray = [{'type':'dog','name':'Buddy'},{'type':'cat','name':'Whiskers'}];

   $('button').click(function(){
     petArray = petArray.map((animal) => {
         animal['color'] = "brown"; 
         return animal;
      });
      console.log(petArray);
   })

  $('p').click(function(){
      petArray[0]['color'] = 'black';
    console.log(petArray);
  });

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

Preserve component state in Angular 4 by saving it when navigating to a different component

Currently, I am faced with a challenge while developing an application using Angular. In one component, users can input data into three selectboxes and then initiate a search to find matching results. Upon clicking on a match, they are taken to another com ...

Angular not recognizing draggable true functionality

I am encountering an issue with a div element: <div draggable = "true" ng-show="showPullDown" class="topPull stretch" draggable > </div> The draggable=true attribute is not functioning as expected. I have attempted to set it through the co ...

In Vue3, when using the `script setup` with the `withDefaults` option for a nested object, its attributes are marked as required. How can this issue

I have defined a props object with certain attributes: interface Props { formList: BaseSearchFormListItemType[], inline?: boolean searchBtn?: { show?: boolean text?: string type?: string size?: string } } const props = withDefaults( ...

I'm curious about the potential vulnerabilities that could arise from using a Secret key as configuration in an express-session

Our code involves passing an object with a secret key's value directly in the following manner --> app.use(session({ secret: 'keyboard cat', resave: false, saveUninitialized: true, cookie: { secure: true } }) I am pondering wheth ...

Assurance of retrieving information

I am looking to extract specific information from the following website . I have implemented Promises in order to retrieve data about planets, then films associated with a particular planet object. My next goal is to access data within the species array ne ...

Resize the div based on the width and height of the window

My goal is to create a system or website that can be fully resizable using CSS and the VW (viewport width) unit. Within this system, I have integrated a GoogleChart that functions with pixels. Now, I am looking for a way to scale the chart using Javascript ...

String validation using regular expressions

Below is the code I am using to validate a string using regular expressions (RegEx): if(!this.validate(this.form.get('Id').value)) { this.showErrorStatus('Enter valid ID'); return; } validate(id) { var patt = new RegExp("^[a-zA- ...

What is the correct way to use variables to reference whether an item is odd or even in an ng-repeat loop?

Is there a way to access the variables $odd and $even within ng-repeat using a variable for reference? Here is what I have attempted: <ng-repeat="item in items" ng-if="$odd">these are odd{{item}}</div> <ng-repeat="item in items" ng-if="$eve ...

Tips for retrieving the most recent number dynamically in a separate component without needing to refresh the page

Utilizing both the Helloworld and New components, we aim to store a value in localStorage using the former and display it using the latter. Despite attempts to retrieve this data via computed properties, the need for manual refreshing persists. To explore ...

Tips for managing an array of observable items

In my current project, I am working with an Angular application that receives a collection from Firebase (Observable<any[]>). For each element in this collection, I need to create a new object by combining the original value with information from ano ...

Analyzing Varied Date Formats

I'm looking to create a function in AngularJS that checks if a given date is after today: $scope.isAfterToday= function(inputDate){ if(inputDate > Date.now().toString()){ return true; } else { return false; } } The iss ...

Utilize AngularJS to monitor the amount of time users spend within the web application and automatically activate an event at designated intervals

Is there a way to monitor how long a user is active on the website and trigger an event once they reach 30 seconds of browsing time? ...

The 'string' Type in Typescript cannot be assigned to the specified type

Within the fruit.ts file, I've defined a custom type called Fruit which includes options like "Orange", "Apple", and "Banana" export type Fruit = "Orange" | "Apple" | "Banana" Now, in another TypeScript file, I am importing fruit.ts and trying to as ...

Vue.js and axios causing an empty array after the page is refreshed

As a newcomer to coding and using vue cli, along with my limited English skills, I apologize if I am unable to articulate the issue clearly. However, I am reaching out to the community for assistance. The code snippet below is from store.js where I fetch ...

React - error caused by an invalid hook call. Uncaught Error: React encountered a minified error with code #

My goal is to incorporate the micro-frontend concept by implementing various react apps. Container Header Dashboard All three are separate applications. I intend to utilize the Header and Dashboard apps within the Container app. For the Header app, it& ...

The utilization of 'fs' in the getInitialProps function is not permitted

Running into an issue while trying to access the contents of a parsed file within getInitialProps when my view loads. The error message "Module not found: Can't resolve 'fs'" is being displayed, and this has left me puzzled - especially cons ...

The dropdown menu fails to update in Internet Explorer

Here is the URL for my website: . On this page, there are two fields - category and subcategory. When a category is selected, the corresponding subcategory should change accordingly. This functionality works smoothly in Google Chrome, however it encounte ...

Using an iframe containing a link to trigger the opening of a colorbox in the

Recently, I encountered a challenge regarding an iframe containing a bar graph. I wanted to achieve that when the graph is clicked, it would open a colorbox with a more detailed graph from the "PARENT" of that iframe. Initially, I managed to get the ifram ...

I need help with a process to extract information from a database and convert it into an object specifically for my situation

Currently, I am utilizing the postgres row_to_json function to retrieve data that has been stored using JSON.stringify(). However, upon retrieval and attempting to parse it with JSON.parse(), an error message stating "unexpected token ," is returned. The ...

*ngFor not functioning properly within Angular ionic modal

While working on my Ionic application with Angular, I encountered an issue with the ngForm not functioning properly inside a modal. I have tried to identify the problem with a simple code snippet: <li *ngFor="let item of [1,2,3,4,5]; let i = index ...