简体   繁体   中英

how to push object ino an array when user inputs value in angularJs

I have multiple input fields under different headings:-

<label>User</label>
  <input type="text" ng-model="a.arr.username" name="arr[0]"/>
  <input type="text" ng-model="a.arr.userdob" name="arr[0]"/>
  <input type="text" ng-model="a.arr.userpanNo" name="arr[0]"/>

<label>Employee</label>
  <input type="text" ng-model="a.arr.empname" name="arr[1]"/>
  <input type="text" ng-model="a.arr.empdob" name="arr[1]"/>
  <input type="text" ng-model="a.arr.emppanNo" name="arr[1]"/>

<label>Daily Workers</label>
  <input type="text" ng-model="a.arr.dwname" name="arr[2]"/>
  <input type="text" ng-model="a.arr.dwdob" name="arr[2]"/>
  <input type="text" ng-model="a.arr.dwpanNo" name="arr[2]"/>

I want to save above data in the format:- [{a.arr.username:any value},{a.arr.empname:any value},{a.arr.dwname:any value}] . But the structure I am getting is:- {a.arr.username:any value,a.arr.empname:any value,a.arr.dwname:any value} . Is there any way to do this?

Where you are storing data you will have to store it like :

a.arr=[];
//here you have to define object for each index before making keys of it.
a.arr[i]={};

尝试这个

 var arr=[]; arr.push({'a.arr.username':$scope.a.arr.username,{'a.arr.empname':$scope.a.arr.empname}})

Basically, you want to make your object as an array of it's properties. I suggest you to leave the code as it is and just add a code to make another controller property which will hold the array of those properties.

To get the array of properties, below code will help you:

var x = {username: "any value", empname: "any value", dwname: "any value"};
var newArr = [];
var properties = Object.keys(x);
for(var i=0;i<properties.length;i++){
    newArr.push({});
    newArr[newArr.length - 1][properties[i]] = x[properties[i]];
};

Let me know if you need to understand anything else regarding this.

Best Regards

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM