JavaScript: aggiornare un array di oggetti

JavaScript: aggiornare un array di oggetti

Possiamo aggiornare un array di oggetti JavaScript con un metodo molto semplice.

Il codice è il seguente:


'use strict';

const arrObjects = [
  {
    id: 1,
    bar: 'Test'
  },
  {
    id: 2,
    bar: 'Foo'
  },
  {
    id: 3,
    bar: 'Baz'
  }
];

let index = 0;

for(let i = 0; i < arrObjects.length; i++) {
    let obj = arrObjects[i];
    if(obj.id === 2) {
        index = i;
        break;
    }
}

arrObjects[index] = {
  id: 4,
  bar: 'Baz'
};

// [{id: 1, bar: 'Foo'},{id: 4, bar: 'Baz'}, {id: 3, bar: 'Baz'}]

In pratica troviamo prima l'indice dell'oggetto che vogliamo aggiornare e quindi usiamo tale indice per aggiornare l'array modificando l'oggetto trovato.

Torna su