Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update multiple object in an array

I want to do bulk update to an array using typescript.

I did it by using for loop.

this.versions = [{ id: 1, VersionName: 'test1' }, { id: 2, VersionName: 'test2' }, { id: 3, VersionName: 'test3' }, { id: 4, VersionName: 'test4' }];
this.selectedVersions = [{ id: 2, VersionName: 'test2' }, { id: 3, VersionName: 'test3' }];
for (let i = 0; i < this.selectedVersions.length; i++) {
  this.versions = this._configuration.updateEveryObjectsByKey(this.versions, this.selectedVersions[i], "Id");
}

updateEveryObjectsByKey(listOfdata: any, data: any, key: string) {
  listOfdata = listOfdata.map(function (item) {
    return item[key] == data[key] ? data : item;
  })
  return listOfdata;
}

But I don't like to use for loop. So let me know how to do bulk update to array using typescript?

like image 233
Ramesh Rajendran Avatar asked Oct 19 '25 16:10

Ramesh Rajendran


2 Answers

You can use ES6's Object.assign, array.find and array.map :

var versions = [{ id: 1, VersionName: 'test1' }, { id: 2, VersionName: 'test2' }, { id: 3, VersionName: 'test3' }, { id: 4, VersionName: 'test4' }];
var selectedVersions = [{ id: 2, VersionName: 'test2 update' }, { id: 3, VersionName: 'test3' }];
var key = "id";
versions = versions.map(el => {
  var found = selectedVersions.find(s => s[key] === el[key]);
  if (found) {
      el = Object.assign(el, found);
  }
  return el;
});
console.log(versions);
like image 114
Faly Avatar answered Oct 21 '25 06:10

Faly


Simple solution to a potentially complex problem.

           $scope.model.ticketsArr.forEach(function (Ticket) {
                if (Ticket.AppointmentType == 'CRASH_TECH_SUPPORT') {
                    Ticket.AppointmentType = '360_SUPPORT'

                }
            });
like image 35
Deathstalker Avatar answered Oct 21 '25 05:10

Deathstalker