Transform a single attribute in an array of objects using angularjs and Javascript to a different value

Within an angularjs controller, the following code is used:

var ysshControllers = angular.module('theControllers', []);

ysshControllers.controller('CommonController',
    function($scope, $http, $route) {
        $scope.dbKey = $route.current.customInput;
        $scope.urlToDb = 'https://' + $scope.dbKey + '/.json';
        $http.get($scope.urlToDb).success(function(data) {
            var values = [];
            for (var name in data) {
                values.push(data[name]);
            }
            $scope.Items = values;
            });
            // Initially order by date and time
            $scope.orderProp = 'ac';
    }
);

This code creates an array object named Items. The keys are labeled as aa, ab, ac, etc. When a user inputs data from a dropdown menu, only values like 1,2,3,4,5 need to be saved. Upon importing back into the website, these values should be converted. For example, 0 corresponds to Bad and 5 corresponds to Very Good. Therefore, when dealing with records under the key name ae, the numeric values 1,2,3,4,5 should be converted to text values: Bad, Okay, Fair, Good, Very Good.

The structure of the data looks like this:

C5_200630_Option 1

   aa:"Option 1"
   ab:"Toyota"
   ac:6499
   ad:"Truck"
   ae:"Tacoma, Silver, 1/2 ton 4wd"
   af:4

An attempt was made using the following line of code:

alert(Object.keys($scope.UsedItems));

This provided values such as 0,1,2,3,4. It appears that the key values within $scope.UsedItems are solely numbers. A method needs to be found to access both the key and value data specifically. Is there a simple way to display the content of the array contents in an alert?

By using this line:

alert(data[name].ad);

The data within each record with the name ad can be referenced. This offers a means to pinpoint a specific item within the record.

A solution has been discovered:

if (data[name].af === "3") {
    data[name].af = "Awesome!";
}

Despite the resolution of the problem at hand, there remains a lack of understanding regarding how to proceed further. If there exists a better approach, please advise.

Answer №1

To create an array, use the following syntax:

let options = ["Low", "Medium", "High"];

Instead of repeatedly checking the value of data[name].priority, you can simplify things by assigning it like this:

data[name].priority = options[data[name].priority];

This will provide you with the desired outcome, as setting data[name].priority=2 corresponds to "High" in the options array.

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

Issue with generating WebGL shaders

As I embark on creating a basic application in WebGl and JavaScript following online tutorials, I encountered a peculiar issue while working on some fundamental shaders. The function responsible for generating the shader program presents itself as follows: ...

What is the process of adding a div to the left side of the parent element in AngularJS

I am trying to append the code on the left side of the click. My current controller code looks like this: demo.$inject = ['$scope']; demo.directive("boxCreator", function($compile){ return{ restrict: 'A', l ...

Filter an object in Typescript and retrieve a single key

Managing a set of checkboxes is essential in assigning roles to new users. While it's possible to filter and retrieve only the checked checkboxes, extracting just the "name" key poses a challenge. The current method involves filtering with a for loop ...

Limitations on Embedding Videos with YouTube Data API

I have been using the Youtube Data API to search for videos, but I am encountering an issue with restricted content appearing in the results. Specifically, music videos from Vevo are showing up even though I only want videos that can be embedded or placed ...

Execute async functions sequentially with a queue and limit to only one function running at a time

Within my javascript code, there is an async function named generateThumbnail. This function is triggered by a specific event, such as clicking on a button. The issue I'm facing is that running the function multiple times concurrently leads to a memor ...

Reactivate IntelliJ IDEA's notification for running npm install even if you have previously selected "do not show again" option

One of the great features in Intellij IDEA is that it prompts you with a notification when the package.json has been changed, asking if it should run npm install, or whichever package manager you use. I have enjoyed using this feature for many years. Howe ...

Add to an array the recently created span element which was inputted through text in AngularJS

Having some difficulty controlling an array object with a list of span values using a watcher in Angularjs. The current setup works partially - when I input span elements, an array is automatically created for each span. When I remove a span element, the ...

Step-by-step guide on retrieving the date from a class and passing it to the test class

Today, I have to complete a task and here's what I have already accomplished: After a brief meeting with the company's CEO, I gathered the following key information: The data must be stored in a single collection Each flight has a unique n ...

Retrieve storage information when an internet connection is unavailable on React Native

One of my recent projects involves creating an application that retrieves data from a URL in the form of an array of objects and then displays this data using FlatList. Upon launching the application, the data is displayed correctly since it's retriev ...

Optimizing load behavior in React using Node.js Express and SQL operations

As someone who is fairly new to programming, I have a question regarding the connection between server and client sides in applications like React and other JavaScript frameworks. Currently, I am working with a MySQL database where I expose a table as an ...

What are the best practices for securely using JSON.stringify in JavaScript?

When I use JSON.stringify on a string that includes <script> tags, the script tags somehow escape and show up in the body of my document, causing unexpected results with the "injected" data. I'm puzzled by how they manage to escape, considering ...

When using phonegap with iOS, HTTP requests consistently return a status of 0 when accessing local files

I've encountered an issue while using Phonegap 3.3.0 on iOS. The HTTP request I'm making always returns 0, regardless of whether the file exists or not! var url = './images/pros/imagefile.png'; var http = new XMLHttpRequest(); http.o ...

The node.js express framework is unable to fetch the URL and data from the node server

Attempting to create a basic application to retrieve data from a nodejs server. But encountering issues with accessing the file in both the browser and POSTMAN. Despite multiple attempts to verify the URLs, I have been unsuccessful. Below are the files i ...

Adding data to an array from a JSON source using Angular 5

When I receive a response from an endpoint, it looks like this: { "data": [{ "volume": 4.889999866485596, "name": "Carton03", "weight": 5.75, "storage": 3 }, { "volume": 2.6500000953674316, "name": "Carton02", "weight": 4.5 ...

Angular has surpassed the maximum call stack size, resulting in a Range Error

I am facing an issue while trying to include machine detail and a button bar in my app. Interestingly, this setup has worked perfectly fine in other parts of the application but is causing errors in the core module. Here is the error message main.ts impo ...

Exploring memory leaks in AngularJS unit tests

Many of us faced with a challenging problem when trying to execute a large number of written unit tests. Personally, I have over 3500 unit tests written in the Jasmine syntax following AngularJS's unit testing guide. These tests are run using the Karm ...

What is the best way to display a loading image and temporarily disable a button for 3 seconds before initiating the process of sending post data from another page via

Is there a way to display a loading image and disable a button for 3 seconds before sending post data from another page using AJAX POST? Once the OK button is clicked, I would like the loading image to appear and the <input type="button" value="Check" ...

Caution: Attempting to access a non-existent 'sequelize' property within a circular dependency in the module exports

Issue Nodemon server.js [nodemon] 2.0.15 [nodemon] to restart at any time, enter `rs` [nodemon] watching path(s): *.* [nodemon] watching extensions: js,mjs,json [nodemon] starting `node server.js` Warning: connect.session() MemoryStore is not designe ...

Unsure about the commit hash referenced in the tsd.json file

Explore the history of angular-ui-router d.ts file using the commit hash Within my tsd.json file, I have the following details: { "version": "v4", "repo": "borisyankov/DefinitelyTyped", "ref": "master", "path": "typings", "bundle": "typings/tsd ...

Leverage the power of the modal component in your ReactJS

I'm facing an issue with the antd library. Even after installing it from the official site and importing the modal component, it's not functioning properly for me. I've carefully checked everything in my code and everything seems to be fine. ...