Enhancing an Angular object with a new property

Currently, I am working on an Angular application that retrieves data from a Web API service. The API sends back JSON objects which are then returned to the controller as an array of objects through the Angular service ($http.get()). This process is quite standard.

My goal is to include a property named "Selected" to each of the objects returned by the API. This particular property serves only for the user interface (UI) purposes and does not require any form of persistence. To achieve this, I thought it would be simplest to iterate through the array of objects and append it manually. That resulted in the following code snippet:

function getData() {
    myService.getData()
        .then(function(data) {
            $scope.myData = data.results;
            // Add a "Selected" property to each object
            $.each($scope.myData, function(item) {
                item.Selected = false;
            });
}

However, upon executing the line "item.Selected = false," an error is thrown stating "Cannot assign to read-only property Selected." This raises the question as to why "Selected" is considered read-only. Is there some internal manipulation happening within Angular when processing objects? What mistake am I making here? Alternatively, should I consider an entirely different approach?

It's important to note that I wish to avoid integrating Selected into the original object structure as it holds no relevance to the object itself.

Answer №1

To include a new attribute in an object, you can utilize underscorejs.

"forEach _.each(list, iteratee, [context]) Loop through a series of elements and pass each one to a specified function as an argument. If provided, the context object will be bound to the iteratee. The iteratee function receives three parameters for each invocation: (element, index, list). When working with JavaScript objects, the arguments passed to the iteratee will be (value, key, list). This method returns the list allowing for method chaining."

"extend _.extend(destination, *sources) This function copies all the properties from source objects to a destination object and then returns the updated destination. Keep in mind that the order matters; any properties with the same name in previous sources will be overridden by those in later sources."

$scope.myData = data.results;
// Add a "Selected" property to each object   

_.each($scope.myData, function(ent) {
    _.extend(ent, {
        Selected : false
    });
});

Answer №2

Instead of the object, your debugger's screenshot reveals that a number (0 in this case) is being received as the 'item' variable, resulting in the error message:

Cannot assign to read-only property 'Selected' of 0

The issue arises because assigning properties to primitives in strict mode triggers the "Cannot assign to read-only property" error, which would otherwise fail silently outside of strict mode.

As noted by JcT, the reason for this is due to $.each passing two parameters to the function - first the index and then the value. Refer to the documentation of $.each:

callback

Type: Function( Integer indexInArray, Object value )

To resolve this issue, ensure that the callback function includes both parameters. Update your code as follows:

function getData() {
    myService.getData()
        .then(function(data) {
            $scope.myData = data.results;
            // Add a "Selected" property to each object
            $.each($scope.myData, function(index, item) { //index was added here!
                item.Selected = false;
            });
}

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 style the background color of the selected option in a <select> element using

Is there a specific style I can use to change the color of a selected option in a dropdown menu? For example: <HTML> <BODY> <FORM NAME="form1"> <SELECT NAME="mySelect" SIZE="7" style="background-color:red;"> <OPTION>Test 1 &l ...

It seems that in Laravel 5.3, it's challenging to add a script to a view for an autocomplete

Currently, I am working with Laravel 5.3 for my internship. However, I have encountered a frustrating issue that I need help with: I am trying to implement an "autocomplete" field on a page, but it doesn't seem to be functioning correctly. The error ...

Enable Parse5's case sensitivity

Recently, I've attempted to parse Angular Templates into AST using the powerful parse5 library. It seemed like the perfect solution, until I encountered an issue - while parsing HTML, it appears that the library transforms everything to lowercase. Fo ...

Is it possible to wait for two asynchronous actions using only one await statement?

I have a situation where I am dealing with a node module that exports a promise to resolve a database connection. Once this connection is resolved, I then need to use it to query records which involves another asynchronous operation. Is it possible to hand ...

instructions to selectively remove additional instructions

In my quest to develop a directive that can impact target elements in various ways, I have encountered three possible scenarios: 1. leaving the element unchanged, 2. removing all other directives before compilation to restrict user interactions (such as ng ...

On page load, refresh the content of the div based on the selected radio button values

My goal is to automatically collect the values of checked radio buttons when the page loads, rather than waiting for a user interaction like clicking a radio button. Below is the JavaScript code I am using: $(function () { updateDivResult(); $(&a ...

Determining the state update value in useEffect using dispatch and payload in Redux

Apologies for the confusion in the title. I am currently working with React and Redux-toolkit. I encountered an issue where when referencing the updated value in the useState set function, I ended up getting the value before the update. I understand that ...

Conceal the visibility of the popover in Onsen UI

Before anyone criticizes me for not trying existing solutions, I have attempted them and unfortunately, they did not work for me. I followed the suggestions in similar questions linked below without success: How to hide popover in onsen ui I am puzzled as ...

Removing the gridlines in a Linechart using Apexcharts

I am experiencing issues with the grid and Nodata options on my Apexchart line chart. noData: { text: none , align: 'center', verticalAlign: 'middle', offsetX: 0, offsetY: 0, style: { color: undefined, fontSize: &apo ...

Avoid typing the URL directly into the address bar to prevent redirection

For instance, if I have a domain (abc.com) with a page abc.com/data-list, how can I prevent users from manually typing in the address bar to access that page? I want to use JavaScript to dynamically update the content section without refreshing the entire ...

Nested UI routing with hidden display

I am working on a website using AngularJS and Ui-router. Index.html <body> <a href="#">Home Page</a> <div ui-view></div> </body> Javascript: .config(function($stateProvider, $urlRouterProvider) { $statePro ...

The question of when to utilize userEvent.click versus fireEvent in React Testing Library

I'm currently diving into the world of React-Testing-Library. One question that I have is regarding testing mouse interaction on an element. I find myself a bit confused about whether to use userEvent.click(element) or fireEvent.click(element). Can b ...

What could be causing an external row to be inserted during the process of writing an excel file in Nodejs?

Currently, I am tackling the challenge of utilizing Nodejs to read and write Excel files with the "XLSX" npm module. While I have managed to successfully read and write data, an unexpected external row is being inserted in place of the first row with the c ...

Transforming a string return method into JSON using REST apis

When I call a Spring method in my controller that returns a String, and consume the web service using Angular's $http module, I receive the following error: SyntaxError: Unexpected token a at Object.parse (native) This is the code snippet from my c ...

What is the solution to incorporating a scrollbar in a popup when I increase the zoom level?

When trying to add a scrollbar to the popup, I am facing an issue where the scrollbar does not appear when zoomed in to 75% or 100%. It works fine for fit screen but not on zoom. Can anyone help me identify what is wrong with my code and suggest how to han ...

Tips for arranging records in Angularjs to give priority to display alphabetically

Hey everyone! I'm currently working on AngularJS to create a table displaying a list of records. My main challenge lies in arranging the table in ascending order, specifically ensuring that the alphabet record (X) appears as the first entry in the tab ...

The NodeJS application experiences a crash if incorrect parameters are provided to the API

Currently, I have built a CRUD API using TypeScript with Node.js, Express, and MongoDB. My goal is to ensure that the API functions correctly when the correct parameters are sent through a POST request. However, if incorrect parameters are passed, the Node ...

The router is unable to direct when an item is clicked

I am encountering an issue with my routing setup - when I click on an item in the list-item component, it does not successfully route to the detail-component. Here is a glimpse of my source code: product-list.component.html: <h1>Product List Compon ...

Ajax is updating the information stored in the Data variable

Recently, I reached out to tech support for help with an issue related to Ajax not executing properly due to Access-Control-Allow-Origin problems. Fortunately, the technician was able to resolve the issue by adding a file named .htaccess with the code Head ...

The code functions perfectly on JSfiddle, but for some reason it halts when implemented on

Unfortunately, the code that was working perfectly on JSfiddle seems to be encountering issues when implemented on a regular HTML site. The content loads fine but there seems to be an error with the preview function after selecting an image. We have colla ...