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

Drawing images on a Canvas using specified coordinates: A step-by-step guide

https://i.stack.imgur.com/YkibI.jpg I've been trying to position images on specific coordinates, but I'm having trouble getting the shapes and angles right. Currently, only the top left corner is matching correctly. var _width, _height; var im ...

Triggering multiple onClick events in React / Material-UI when used within a data.map() loop

My English may not be perfect. {data.sort(getSorting(order, orderBy)) .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage) .map(n => { {/*........*/} <Button onClick={this.handleLsClick}> Open Menu < ...

Quantities with decimal points and units can be either negative or positive

I need a specialized input field that only accepts negative or positive values with decimals, followed by predefined units stored in an array. Examples of accepted values include: var inputValue = "150px"; <---- This could be anything (from the input) ...

What could be causing VueJs2 computed properties to not update?

Check out this updated grid example from the official examples. In my application, I need to reposition the sortOrders array. created: function () { var vm = this; this.columns.forEach(function (key) { vm.sortOrders[key] = 1 }) ...

Tips for transferring data from Express to .ejs file during redirection in Node.js

When I submit the login form in my login.ejs file, the page redirects if the details are correct. If the password is wrong, however, I want to display a message in the .ejs file indicating this. Below are the details: Here is the code in my app.js file - ...

I am looking to implement a straightforward drag-and-drop feature using jQuery

Is it possible to drag and select 4 buttons in a browser, similar to how you would do on Windows, using jQuery locally? ...

Error Found: AngularJS Error State

Currently, I am facing a task in Angular where I need to merge two components in state.js. Being new to this, I added the code but encountered a state error that I cannot pinpoint the source of. I believe I followed the correct steps, but there seems to be ...

Broadening the capabilities of jQuery through a versatile function

Currently, I am in the process of developing a generic function for my website using jQuery that will be utilized across the entire site to display success or error messages. After careful consideration, I have decided to transform this function into a plu ...

Decoding SQS POST messages using node.js

I am faced with the challenge of setting up communication between a web server and a worker using an SQS. The process involves uploading an image to an S3 bucket through the server, which then sends a message to the SQS for the worker to retrieve, resize, ...

Enhance the functionality of your current JavaScript code by adding value during the change event

Looking for a way to make a javascript widget that displays a data chart interactive by allowing users to change the theme? By using a dropdown box, users can select a new theme and instantly see it applied to the widget. Check out the code below: <sc ...

What are the benefits of having a service dedicated to interacting with a single entity, while another service is responsible for handling a group of entities?

Imagine we have a User entity. Would it be better to have two smaller services (User and Users) or one larger service that manages both individual Users and collections of Users? If it's the latter, what's the recommended practice for naming the ...

What is the process for activating focus on an input element within a mat-select component?

How can I activate the cursor on the HTML input element (search field) using a keyboard inside mat-select? It functions properly when using a mouse, but in order to meet WCAG requirements, it needs to be fully functional with keyboard navigation. Click h ...

Pass data from a Firebase JavaScript callback function in the Data Access Layer (DAL) to another function in the controller

I have been developing a basic chat application that enables users to send messages in a group chat and see them instantly updated. To achieve this, I opted for Firebase and spent time familiarizing myself with its web API. However, I encountered difficult ...

Manipulating deeply nested state data in Vuex actions can be a challenge

When working in the store, I have an action that updates certain data. The action is structured like this: setRoomImage({ state }, { room, index, subIndex, image }) { state.fullReport.rooms[room].items[index].items[subIndex].image = image; co ...

Delete outdated information using Google Apps Scripts when the date is less than the current date plus a specified number of days

I have a Google Sheet where I need to filter out entries based on the number of days since the last check. Specifically, I want to keep only those entries where the number of days since the last check is greater than 10. You can find the Sheet here. fu ...

Leveraging checkbox selections to communicate with the controller in Angular JS

I am working with a set of checkboxes that are dynamically populated from a database. The value of each checkbox corresponds to a Book Id. My challenge now is figuring out how to pass the selected book Ids to my controller when the user clicks the Save bu ...

The sinuous waveform in JavaScript

track : function(x, y, top, ampl) { return { top : top + 2, x : x + ampl * Math.sin(top / 20), y : (top / this.screenHeight < 0.65) ? y + 2 : 1 + y + ampl * Math.cos(top / 25) }; } This specif ...

The jQuery Deferred feature on Ajax is failing to properly pass the array in the data option as an array, instead converting

I am facing an issue in my application where I want to use jQuery deferred to handle Ajax success and error uniformly from a central location. It works perfectly fine when I pass strings in the data option, but when I try to pass an array, it gets sent as ...

What is the method to activate the ability to select multiple rows in an AngularJS

I have created an HTML table and used ng-repeat to display items in the table. However, I am unable to select multiple rows in the table. How can I achieve this using the control key? Thank you! <div class="table_bg"> <table datatable="ng" dt-opt ...

How to use ajax() to return multiple arrays successfully in jQuery

Hey everyone, I'm working on an AJAX function in jQuery that parses an XML file, creates an array on success, and wants to return multiple arrays on callback. Is it possible? If so, how can I achieve this? Please guide me through this. var arr1 = new ...