angularjs将值推送到对象中
我有一个JSON对象,我想把数组值推送到JSON中angularjs将值推送到对象中,angularjs,Angularjs,我有一个JSON对象,我想把数组值推送到JSON中 $scope.customerObjArray = ['34343434','73473333434']; $scope.jointUsersObj = { "branchAssociated": { "isGridBranch": false }, "customerNumber": "
$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];
}
好吧,你正在这样做: 对于
$scope.customerObjArray
中的每个编号n
,将$scope.jointuserObj
的属性customerNumber
更新为n
你真正想做的是:
对于$scope.customerObjArray
中的每个编号n
,使用属性customerNumber
复制$scope.jointUserObj
试试这个:
$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]
});
}
$scope.jointUserObjects=[]//这是一个用户数组
对于(变量i=0;i<$scope.customerObjArray.length;i++){
$scope.jointUserObjects.push({
branchAssociated:{
isGridBranch:false
},
customerNumber:$scope.customerObjArray[i]
});
}
只需声明一个数组并将对象推送到该数组
$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);
}
$scope.customerObjArray=['3434','73473333434'];
$scope.jointUsersObj={
“branchAssociated”:{
“isGridBranch”:false
},
“customerNumber”:”
};
var jointUsersArray=[];
对于(变量i=0;i<$scope.customerObjArray.length;i++){
$scope.jointUsersObj.customerNumber=$scope.customerObjArray[i];
push($scope.jointUsersObj);
}
这根本不是AngularJS的问题;我们可以用简单的JavaScript解决这个问题。假设您有一个客户数组和一个对象模板,您可以简单地迭代该数组并将每个客户映射到一个对象:
const customers=['123','456'];
常量模板={
branchAssociated:{
isGridBranch:false,
},
};
const mappedCustomers=customers.map(customer=>{
const obj=角度复制(模板);
template.customerNumber=客户;
返回obj;
});
const json=json.stringify(mappedCustomers);
您仅将数字从$scope.customerObjArray
推送到JointUserArray
而不是对象
$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);
}