需要更新对象数组的所有对象中的属性值

时间:2015-10-20 06:41:05

标签: angularjs underscore.js

在我的angularjs应用程序中有一个对象数组,如下所示:

$scope.rowData = [{
    "expNum": "678",    
    "itemHr": "10", 
    "highRe": "C"
    }, {
    "expNum": "978",    
    "itemHr": "3",  
    "highRe": "Y"
}]

现在在点击事件中,我需要将数组中每个对象的'itemHr'更新为一些新值,比如说(25)。我不想创建新的对象数组而只修改现有的对象。如果我们可以使用angularjs实用程序来执行它或下划线库,那么对我来说都很好。任何人都可以帮助我。

2 个答案:

答案 0 :(得分:18)

为什么vanila js没有for循环?

#include <stdio.h> 
#include <string.h>

#define SIZE 500 

void duplicateRemover(char *, const int);

int main(void)
{
    char someString[SIZE];

    puts("Enter text: ");
    fgets(someString, SIZE, stdin);

    someString[strcspn(someString, "\n")] = 0;

    printf("\n\n%s\n\n", "Text without repeated words: "); 
    duplicateRemover(someString, SIZE);
}

void duplicateRemover(char *arrayPtr, const int sizeP)
{
    char wordTable[sizeP][sizeP], *tokPtr;
    size_t i, j, k, l;

    tokPtr = strtok(arrayPtr, " ");

    strcpy(wordTable[0], tokPtr);

    for(i = 1; (tokPtr = strtok(NULL, " ")) != NULL; i++)
        strcpy(wordTable[i], tokPtr);

    for(j = 0; j <= i; j++) 
        for(k = j + 1; k <= i; k++) 
            if(strcmp(wordTable[j], wordTable[k]) == 0) {
                for(l = k; l < i; l++)
                    strcpy(wordTable[l], wordTable[l + 1]);
            k = j; 
            i--;
            }

    for(l = 0; l <= i; l++)
        printf("%s ", wordTable[l]);
}

或下划线

for(var i = 0; i<$scope.rowData.length; i++)
{
   $scope.rowData[i].itemHr = 25;
}

或有角度的

_.each($scope.rowData, function(item){ item.itemHr = 25;});

&#13;
&#13;
angular.forEach($scope.rowData,function(item){ item.itemHr = 25; });
&#13;
    var app = angular.module("myApp", ['ui.bootstrap']);
 
    app.controller("maincontroller", function($scope) {
       $scope.rowData = [{
            "expNum": "678",    
            "itemHr": "10", 
            "highRe": "C"
           }, {
            "expNum": "978",    
            "itemHr": "3",  
            "highRe": "Y"
           }];
       $scope.update = function(){
          for(var i = 0; i<$scope.rowData.length; i++)
          {
             $scope.rowData[i].itemHr = 25;
          }
         
       }

    });
&#13;
&#13;
&#13;

答案 1 :(得分:2)

angular.forEach($scope.rowData, function(item,index){
   item["itemHr"] = "25";
})