简体   繁体   中英

Update a array field value using field index in Angularjs array

$scope.MyArray = [
  {id:'01', name:'test1', dept:'abc1', address: 'xyz1'},
  {id:'02', name:'test2', dept:'abc2', address: 'xyz2'},
  {id:'03', name:'test3', dept:'abc3', address: 'xyz3'}
];

This is my array list, I have to update the field using the column index,

for example I have a index value [2] which is field dept .

To update the field value as def at the field of dept of the row 01 .

Expected result is,

$scope.MyArray = [
  {id:'01', name:'test1', dept:'def', address: 'xyz1'},
  {id:'02', name:'test2', dept:'abc2', address: 'xyz2'},
  {id:'03', name:'test3', dept:'abc3', address: 'xyz3'}
];

Before accessing dept you need to access the object where you want to make change.

You can use map which will create a new array and inside array callback check for the id of the object and if that matches then update the dept of that object

 var MyArray = [{ id: '01', name: 'test1', dept: 'abc1', address: 'xyz1' }, { id: '02', name: 'test2', dept: 'abc2', address: 'xyz2' }, { id: '03', name: 'test3', dept: 'abc3', address: 'xyz3' } ]; const newArray = MyArray.map((item, index) => { if (item.id === '01') { return Object.assign({}, item, { dept: 'newDept' }) } return item; }); console.log(newArray)

You need to access the object using javascript map function and then you can use Object.keys on that object to get keys and index.

Later you can check for that index using if .

Here is the working example:

    var MyArray = [
      {id:'01', name:'test1', dept:'abc1', address: 'xyz1'},
      {id:'02', name:'test2', dept:'abc2', address: 'xyz2'},
      {id:'03', name:'test3', dept:'abc3', address: 'xyz3'}
    ];

    var changedArray = MyArray.map((item, index) => {
      Object.keys(item).map((key, i) => {
        if(i === 2) {
            return item[key] = 'test' //you can add dynamic value instead of 'test'.
        }
      })
      return item;
    });

   console.log(changedArray);

output:

changedArray = [
  { id: '01', name: 'test1', dept: 'test', address: 'xyz1' },
  { id: '02', name: 'test2', dept: 'test', address: 'xyz2' },
  { id: '03', name: 'test3', dept: 'test', address: 'xyz3' }
]

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