Copying an object from one to another using Angular JS within a loop

Attempting to transfer a portion of a json object into another json object (acting as a filter), inside a for loop and under a conditional statement, proves unsuccessful.

The following method works when creating an array:

$scope.candidats=[];
for (i=0;i<omegaCandidats.length;i++){
    if (omegaCandidats[i].dateRdv==date){ 
        $scope.candidats.push(
            {
             "id"       :omegaCandidats[i].id,
             "prenom"   :omegaCandidats[i].prenom,
             "nom"      :omegaCandidats[i].nom,
             "heure"    :omegaCandidats[i].heure,
             "dateRdv"  :omegaCandidats[i].date
            }
        )
    };
};

This method may seem logical but sadly does not work as intended:

$scope.candidats=[];
for (i=0;i<omegaCandidats.length;i++){
    if (omegaCandidats[i].dateRdv==date){ 
        $scope.candidats[i] = omegaCandidats[i];
    };
};

Although this method technically functions, it only retrieves one value from the loop rendering it pointless:

$scope.candidats=[];
for (i=0;i<omegaCandidats.length;i++){
    if (omegaCandidats[i].dateRdv==date){ 
        $scope.candidats[0] = omegaCandidats[i];
    };
};

Answer №1

Have you considered implementing a filter?

$scope.candidats = omegaCandidats.filter(function(c){ 
    return c.dateRdv == date;
});

Answer №2

If you want to filter an array, you can utilize the filter method like so:

$scope.applicants = alphaApplicants.filter(function(person) {
    return person.interviewDate == date;
});

Answer №3

Here is a possible solution:

$scope.candidates=[];
    for (i=0;i<omegaCandidates.length;i++){

        if (omegaCandidates[i].appointmentDate==date){ 

            //$scope.candidates.push(omegaCandidates[i]);

            $scope.candidates.push(angular.copy(omegaCandidates[i]));
            //copy will create a new reference for your object.
        };
    };

The initial code does not seem logical to me:

$scope.candidates=[];
    for (i=0;i<omegaCandidates.length;i++){
        if (omegaCandidates[i].appointmentDate==date){ 
            $scope.candidates[i] = omegaCandidates[i]; // This won't work because $scope.candidates[i] is not defined.
            // It would also result in an inconsistent 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

Previewing Jquery script with live interactive effect using Javascript

Looking to create a page where a sentence can be written and displayed in a well-designed format on the right using Jquery live preview. However, currently the design only loads after writing and reloading the page. Any suggestions on how to generate the ...

Is it possible to repeatedly activate a function using onmousedown just like with onkeydown?

My goal is to have the onmousedown event trigger repeatedly when the left mouse button is held down, instead of just once upon clicking. Currently, it only fires a single time. wHandle.onmousedown = function (event) { console.log('mouse b ...

How can I use AngularJS resource to fetch data from a URL that requires both query parameters and post data?

Requirement: To send data to an endpoint using a post of data, include the startdate and endate in the querystring of the url. Here's an example: The data payload should only contain the locationIDs and Criteria as shown below. The Resource Definiti ...

Is there a more efficient method for referencing a multi-dimensional array in Java?

As a newcomer to Java, I've been assigned a coding project by my instructor. My task is to create a Java program that assists travelers when visiting different countries. Currently, I'm facing a challenge in finding an efficient way to translate ...

Providing Node-server with Vue.js Server Side Rendering

I've been attempting to deploy the Hackernews 2.0 demo on my Digital Ocean droplet but have hit a roadblock. npm run start starts the server on port :8080. npm run build is used for production builds. The specific build tasks can be found below: ...

Managing business logic in an observable callback in Angular with TypeScript - what's the best approach?

Attempting to fetch data and perform a task upon success using an Angular HttpClient call has led me to the following scenario: return this.http.post('api/my-route', model).subscribe( data => ( this.data = data; ...

JavaScript duplicate function is malfunctioning

Check out this jsfiddle link: https://jsfiddle.net/3o38nbzs/4/ When I clone an object, I am able to move the clone but it does not respond to click events. https://jsfiddle.net/L5mg87jm/ When I clone an object in this example, the clone remains static. T ...

The operation malfunctions if the variable input is below 50, causing it to produce inaccurate results

The function "calcFinalTotal()" was created to calculate the post-tax discount on a purchase of items that were previously totaled and stored in an input tag with the ID of "totaltaxamount". This function applies a 10% discount to orders between $50 to $ ...

Monitor the true/false status of each element within an array and update their styles accordingly when they are considered active

Currently, I am attempting to modify the active style of an element within an array. As illustrated in the image below - once a day is selected, the styles are adjusted to include a border around it. https://i.stack.imgur.com/WpxuZ.png However, my challe ...

Trigger a re-render in React using setState(null) and forceUpdate()

When using react 16, setState(null) no longer triggers an update according to the official documentation: The new behavior for calling setState with null is that it does not trigger an update. This gives you the control in the updater function to decide ...

Error: The function this.saveAlpha is not recognized in the current context at eval

This code features a start button, stop button, and a timer. The goal is to retrieve information from the phone using events like DeviceOrientationEvent, which includes properties such as absolute, alpha, beta, and gamma (referenced in this link: here). I& ...

Iterate over a series of button elements within a loop in order to dynamically control corresponding input fields

Having trouble looping through an array with JavaScript/jQuery to display data and remove contents with button clicks. Original Code in Question HTML <textarea rows="4" cols="40" id="sds">Apple Banana Grape Orange</textarea> <input type=" ...

Delivering information to personalized components using React Bootstrap

I am working with a custom styled checkbox that is part of a mapped data array. {nfcArray && nfcArray.map((item, key) => { return ( <tr class="hover"> <td className="cell_style pl-3 pl-lg-5"> ...

Tips for iterating through a list of checked values using v-for

Currently working on a feature to create a checkbox that allows only one selection. <div id="app"> <div v-for="(question, index) in questions"> <input type="checkbox" value="question.value" v-model ...

Send an AJAX request to the specified `httpost` action method without any page refresh to load the

Today I have an interesting challenge that's been a brain teaser for me. While I may not be an expert in ASP.Net MVC4, I'm excited to tackle something new. The ultimate goal is to create a dynamic tree view for partial pages within a standard pag ...

A method for sorting an array of characters based on the numerical values within

Can someone help me organize this vector of chr in numerical order? x=c("class 1", "class 2", "class 4", "class 7", "class 5", "class 3", "class 6", "class 10", "class 9", "class 11", "class 8", "class 12", "class 21") I want the result to be ordered by ...

How can you retrieve a C# variable within JavaScript while using Selenium?

When working with the code below, I encountered an error stating "Linklocation is not defined". How can I properly access the variable within my JavaScript code? IWebElement link = driver.FindElement(By.LinkText("soemtext")); String linkLocation ...

Function fails to execute after drop-down menu selection

I set up a double drop-down feature and implemented my function calling code. However, after choosing an option from the drop-down menus, the function is not getting executed. The purpose of the code is to trigger a specific function based on the selectio ...

Exploring and cycling through numerous links using Selenium WebDriver in a node.js environment

Decided to switch from Casper.js to Selenium for access to more tools. Currently trying to loop through multiple links and navigate them using node.js along with selenium-webdriver. Struggling to find any helpful documentation or examples, as I keep enco ...

The integration of Firebase Google Auth seems to encounter issues when used on the Vercel

My experience with Vercel deployment has been quite interesting. While I find that Google authentication works seamlessly on localhost, it seems to encounter an issue when deployed on Vercel. Specifically, after logging out, the currentUser variable always ...