Using AngularJS to evaluate a string within a function in order to access a property within a JSON array

Unfortunately, I am struggling to come up with a specific title for what I am attempting to achieve. The issue at hand involves manipulating a JSON list within an angular framework. Below is an example of the structure:

$scope.users =
    {
        // The list name and "title" must match
        Guest:
        {
            title: 'Guest',
            list:
            [
                { id: "0", name: "Stephen" },
                { id: "1", name: "Mitch"},
                { id: "2", name: "Nate"},
                { id: "3", name: "Rob" },
                { id: "4", name: "Capt. Jack"},
                { id: "5", name: "Herman" }
            ]

        },
        Admin:
        {
            title: 'Admin',
            list:
            []
        }
    };

The challenge is to dynamically assess a string (for instance, "Guest," "Admin," or any other user-group yet to be created) in order to transfer a user from one user-group to another.

The function in question appears as follows:

$scope.moveUser = function(fromId, toId, index) {
        scope.users.toId.list.push(scope.users.fromId.list[index]);
        scope.users.fromId.list.splice(index, 1);
};

"fromId" and "toId" are strings that should represent the name of a user-group ("Admin" or "Guest"). Presently, the function attempts to locate a JSON field named "toId" and encounters errors if none exists. How can I first evaluate the string so that if "toId" equals "Guest" and "fromId" equals "Admin," my function alters to:

scope.users.Guest.list.push(scope.users.Admin.list[index]);
scope.users.Admin.list.splice(index, 1);

Answer №1

Revise your $scope.moveUser method like this:

$scope.moveUser = function(fromId, toId, index) {
    $scope.users[toId].list.push($scope.users[fromId].list[index]);
    $scope.users[fromId].list.splice(index, 1);}

This adjustment has been successful.

Answer №2

If my interpretation is accurate:

$scope.switchUser = function(startId, endId, position) {
        if (users.hasOwnProperty(startId) && users.hasOwnProperty(endId)) {
          scope.users.endId.list.push(scope.users.startId.list[position]);
          scope.users.startId.list.splice(position, 1);
          return true;
        } else {
          return 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

What causes two identical div containers to display different results when navigating using a keyboard on a radio button?

How can I wrap a radio button group with a 200px width and maintain proper keyboard navigation? I noticed that when I implement a parent div using a Container component const Container = ({ children }) => ( <div style={{ width: "200px" }} ...

Restricting input in Angular using negative regular expressions - a new approach to input restriction directive

UPDATE: Please feel free to include additional validations that may be helpful for others within this straightforward directive. -- I am currently in the process of creating an Angular Directive that restricts the characters inputted into a text box. Whi ...

AngularJS 1 - CSS glitch occurs when navigating between tabs

Upon loading my homepage, it appears as follows: https://i.sstatic.net/CTlj1.png Initially, certain rows were filled with a blue background color using ng-class, specifically "row-answered-call" as shown below: <tr ng-repeat="item in list" ng-class=" ...

Tips for showcasing the information of an object on the client side with JSON

public class ProductController : ApiController { Product[] items = new Product[] { new Product { Id = 1, Name = "Banana Bread", Category = "Bakery", Price = 2 }, new Product { Id = 2, Name = "Kite", Category = "Toys", Pri ...

Display only the relevant search results using ng-show in AngularJS

By utilizing the code below, I am able to filter results where all entries are displayed on the page: <body ng-app=""> <div ng-init="friends = [{name:'John', phone:'555-1276'}, {name: ...

Step-by-step guide on triggering a button using another button

I have a unique question that sets it apart from others because I am looking to activate the button, not just fire it. Here is my syntax: $("#second_btn").click(function(){ $('#first_btn').addClass('active'); }) #first_btn ...

Combine a segment from two arrays into a single array

I have two arrays and I want to merge them into one while extracting only certain elements... I am using axios with vueJS. (9) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}] 0: Nombredejours: 1.5 Task: {id: "52edcb0e-450f-4de7-b70d-b63e0 ...

Storing the $_session['username'] variable within an ajax function

I've been working on a script and I've reached the point where I need to add protection. However, I'm having trouble retrieving the $_session['username']. I can't use cookies because they are vulnerable to being faked, posing ...

Listener for a special event in Three.js

As I embark on my journey with Three js, I find myself in search of a unique event listener that seems to elude me online. I am curious whether it is feasible to execute a specific action when the first-person viewer enters an object. Any advice would be ...

When the input field is clicked, the file:/// URL is sent

Currently, my HTML page contains a form that includes an input field for URLs. Ideally, upon typing in the URL and clicking the button, I intend to be redirected to that website. However, the issue lies in the fact that instead of redirecting me to the p ...

Unit testing in AngularJS: Initializing the controller scope of a directive

Here is the code for a directive with a separate controller using the "controller as" syntax: 'use strict'; angular.module('directives.featuredTable', []) .controller('FeaturedTableCtrl', ['$scope', function ($sco ...

utilize the vue component data

I have created a basic component, but I am encountering an issue where attempting to access the component's data returns undefined. Here is my code snippet: Vue.component({ template:`<div>{{message}}</div>`, data() { return { com ...

The speed at which Laravel loads local CSS and JS resources is notably sluggish

Experiencing slow loading times for local resources in my Laravel project has been a major issue. The files are unusually small and the cdn is much faster in comparison. Is there a way to resolve this problem? https://i.stack.imgur.com/y5gWF.jpg ...

Error: Invalid JSON format. Expected a value in the JSON object, as well as property names to be enclosed in double quotes

Hey there, I'm currently dealing with JSON data in my Python file: import json userData = '''[ { "userID" : "20", "devices" : { "360020000147343433313337" : "V33_03", "3f0026001747343438323536" : "Door_03", ...

There seems to be a problem with a method call. The error message is stating that the method 'map' was called on a null object. Can

Currently, I am working on extracting data from a Rest API within a Dart/Flutter application. In the provided JSON, there is a field named data at the root level that holds a list of Words. My goal is to retrieve a List<ArticalList> using this JSON a ...

The Chrome browser does not recognize Sys.WebForms

I am encountering an issue with my Web-Application when trying to perform partial updates. The error message "Sys.WebForms is undefined in Chrome (latest version)" keeps popping up. Despite my extensive research efforts, I have not been able to find a solu ...

The issue with the jQuery Mobile onclick event is that it fails to remove the ui-disabled

Ever since I delved into coding with jQuery Mobile, I've noticed a change in the function that once effortlessly removed the "ui-disabled" class. Now, all it does is display an alert message... Snippet from the HTML code: <div data-role="navbar ...

Why isn't my content appearing correctly on different pages?

This ecommerce site is my very first project using React. I have created pages for Contact, Login, and more. The footer and other components display correctly on the home page, but when navigating to other pages, the content appears shortened. For referen ...

Creating a Bottom-Up Menu in React Native: A Step-By-Step Guide

Need help figuring out how to create a menu that pops up from the bottom when a button is clicked. Any advice on where to start? If you have any guidance or insights, they would be highly appreciated. ...

Sending multiple objects using Ajax and fetching them in PHP

I'm facing an issue with posting a form and an array to my PHP script. My current approach involves using the following code: var json_data = JSON.stringify(data_vendor); //array to be posted $.ajax({ url: &ap ...