1

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?

Claies
  • 21,481
  • 3
  • 49
  • 75
Ramesh Rajendran
  • 32,579
  • 35
  • 130
  • 205
  • What about [the question you asked 25 minutes ago](https://stackoverflow.com/questions/46913059/bulk-delete-in-array-by-using-typescript) ? It has 7 answers. – Jeremy Thille Oct 24 '17 at 14:48
  • That's related with multiple delete by using findIndex or filter. But this multiple update by using map or else. So I have asked separate question . – Ramesh Rajendran Oct 24 '17 at 14:49
  • 1
    Ok, fair enough – Jeremy Thille Oct 24 '17 at 14:50
  • Your current code doesn't actually modify the original objects. Instead it will completely replace the original object with the new object from `selectedVersions`. Is this a functionality you want to keep? – BeetleJuice Oct 24 '17 at 14:58
  • @BeetleJuice Actually I don't think a much difference between update and replace ! – Ramesh Rajendran Oct 24 '17 at 15:01
  • 1
    There's a big difference between update and replace, for example you have `{ id: 0, a: 2, b: 3 }`. Update with `{ id: 0, a: 3 }` will result in `{ id: 0, a: 3, b: 3 }` while replace will result in `{ id: 0, a: 3 }`. – cyr_x Oct 24 '17 at 15:07

2 Answers2

6

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);
Faly
  • 12,529
  • 1
  • 16
  • 34
1

Simple solution to a potentially complex problem.

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

                }
            });
Deathstalker
  • 572
  • 5
  • 6