angularjs将值推送到对象中

时间:2016-01-08 06:31:10

标签: angularjs

我有JSON对象,我想将数组值推送到JSON。

      $scope.customerObjArray = ['34343434','73473333434'];

        $scope.jointUsersObj = {
            "branchAssociated": {
               "isGridBranch": false
            },             
            "customerNumber": ""              
        };

     for(var i = 0; i < $scope.customerObjArray.length; i++){
         $scope.jointUsersObj.customerNumber = $scope.customerObjArray[i];                
     }

我希望以下列方式输出

{
   "branchAssociated": {
     "isGridBranch": false
    },             
    "customerNumber": "34343434"              
},
{  
   "branchAssociated": {
       "isGridBranch": false
    },             
    "customerNumber": "73473333434"              
}

3 个答案:

答案 0 :(得分:1)

嗯,你这样做:

n中的foreach号$scope.customerObjArray,将customerNumber的属性$scope.jointUsersObj更新为n

你真正想做的是:

n中的$scope.customerObjArray个号码,复制$scope.jointUsersObj,其中customerNumber属性为n

试试这个:

$scope.jointUserObjects = [] // this is an array of users
for(var i = 0; i < $scope.customerObjArray.length; i++) {
     $scope.jointUserObjects.push({
        branchAssociated: {
              isGridBranch: false
        },             
        customerNumber: $scope.customerObjArray[i]    
     }); 
 }

答案 1 :(得分:0)

这根本不是一个AngularJS问题;我们可以用简单的JavaScript解决它。假设您有一组客户和一个对象模板,您可以简单地遍历数组并将每个数据映射到一个对象:

const customers = [ '123', '456' ];
const template = {
  branchAssociated: {
    isGridBranch: false,
  },
};

const mappedCustomers = customers.map( customer => {
  const obj = angular.copy( template );
  template.customerNumber = customer;

  return obj;
});

const json = JSON.stringify( mappedCustomers );

答案 2 :(得分:-2)

只需声明一个数组并将对象推送到该数组。

$scope.customerObjArray = ['34343434', '73473333434'];

$scope.jointUsersObj = {
    "branchAssociated": {
        "isGridBranch": false
    },
    "customerNumber": ""
};
var jointUsersArray = [];
for (var i = 0; i < $scope.customerObjArray.length; i++) {
    $scope.jointUsersObj.customerNumber = $scope.customerObjArray[i];
    jointUsersArray.push($scope.jointUsersObj);
}