• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

305
Views
¿Cómo puedo usar las funciones de AngulsJS para simplificar un bucle for?

Tengo el siguiente ciclo y me preguntaba si hay una forma más eficiente de hacerlo en AngularJS. Entonces, quiero recorrer cada elemento en ListA y si no existe en ListB, entonces quiero empujar el elemento de ListA a ListB. Pero el descanso; detiene el ciclo, no pasa por todos los elementos en ListA

 for (item of $scope.ListA) { let found = false; for (obj of $scope.ListB) { if (obj.Name == item.Name && obj.Field == item.Field && obj.DisplayName == item.DisplayName) { found = true; // console.log("double found !"); break; } } if (!found) $scope.ListB.push(newObj); }

¿Cómo puedo hacer esto usando las funciones de AngularJS?

almost 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

No sé si hay alguna funcionalidad específica de angularjs, pero suponiendo que ListA y ListB solo sean matrices de JavaScript, puede usar métodos de matriz estándar para simplificar su solución.

Por ejemplo, aquí uso array.filter , array.some y ... spread operator:

 // Scope example const $scope = { ListA: [ { Name: 'name1', Field: 'field1', DisplayName: 'displayName1' }, { Name: 'name2', Field: 'field2', DisplayName: 'displayName2' }, { Name: 'name3', Field: 'field3', DisplayName: 'displayName3' }, ], ListB: [ { Name: 'name2', Field: 'field2', DisplayName: 'displayName2' }, { Name: 'name4', Field: 'field4', DisplayName: 'displayName4' }, ], }; // A function that checks if a list contains an item const hasItemInList = (item, list) => { // Here we use "array.some" method, which returns "true" if condition is true for any of the array items return list.some(listItem => listItem.Name == item.Name && listItem.Field == item.Field && listItem.DisplayName == item.DisplayName ); } // Getting the array of items that should be added to the listB, // Here we use "array.filter" to filter the items of array by provided condition const itemsToAdd = $scope.ListA.filter(item => !hasItemInList(item, $scope.ListB)); // And here we push all the items to the listB, // we use a spread operator "..." here to push all the items of array at once $scope.ListB.push(...itemsToAdd); console.log($scope.ListB);

Métodos de matriz: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

almost 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error