Tengo este código javascript/jQuery:
var json = [ { id: 0, text: 'enhancement' }, { id: 1, text: 'bug' }, { id: 3, text: 'invalid' }, { id: 4, text: 'wontfix' } ]; delete json[2] console.log(json) <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>Este código elimina la clave de matriz 2. Pero necesito una reindexación después de eso, para poder acceder a los otros 3 valores como:
json[0] json[1] json[2]¿Cómo puedo darme cuenta de esto?
Use splice en lugar de delete como se muestra a continuación ( empalme de W3schools ):
json.splice(target_index,1);Lea la página de Mozila sobre el método de empalme para obtener más información.
Si no desea mutar el valor, simplemente puede filtrar la matriz
json.filter((i, idx) => idx !== 2)puede reindexar simplemente usando
json.filter(function(){return true;})aquí hay una demostración de trabajo.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("#delete").click(function(){ var json = [ { id: 0, text: 'enhancement' }, { id: 1, text: 'bug' }, { id: 3, text: 'invalid' }, { id: 4, text: 'wontfix' } ]; delete json[2] console.log(json.filter(function(){return true;})) }); }); </script> </head> <body> <button id="delete">delete</button> </body> </html>