Tengo una matriz de objetos que tiene submatrices, quiero eliminar el objeto de subarreglo según el índice de ambos niveles.
Por ejemplo, si quiero eliminar un objeto con id: 12, debo pasar firstIndex = 0 y secondIndex = 1; Por favor, tenga en cuenta lo mencionado anteriormente, por ejemplo: es para una mejor comprensión de la pregunta y no para eliminar el elemento por identificación, debe eliminarse solo en función del índice (el caso de uso es diferente y el índice se recibe de una fuente diferente).
const array = [ { id: 1, row: [ {id: 11, value: x}, {id: 12, value: y}, {id: 13, value: z}, ], }, { id: 2, row: [ {id: 21, value: a}, {id: 22, value: b}, {id: 23, value: c}, ], } ] firstIndex = 1, secondIndex = 2 const result = [ { id: 1, row: [ {id: 11, value: x}, {id: 12, value: y}, {id: 13, value: z}, ], }, { id: 2, row: [ {id: 21, value: a}, {id: 22, value: b}, ], } ] firstIndex = 0, secondIndex = 1 const result = [ { id: 1, row: [ {id: 11, value: x}, {id: 13, value: z}, ], }, { id: 2, row: [ {id: 21, value: a}, {id: 22, value: b}, {id: 23, value: c}, ], } ]
const result = array.map((el, i) => (i === firstIndex) && el.rows.map(elm, (elm, index) => (index === secondIndex ) && elm.splice(index, 1)
))
Puede eliminar el elemento de la matriz mediante un método de empalme como este:
const array = [ { id: 1, row: [ {id: 11, value: 'x'}, {id: 12, value: 'y'}, {id: 13, value: 'z'}, ], }, { id: 2, row: [ {id: 21, value: 'a'}, {id: 22, value: 'b'}, {id: 23, value: 'c'}, ], } ] firstIndex = 1, secondIndex = 2; array[firstIndex].row.splice(secondIndex, 1); console.log(array)
Agregando el encadenamiento opcional: ?
usted asegura que el código funciona incluso si sus índices son incorrectos, entonces simplemente no cambia nada y no obtendrá un error
const array = [ { id: 1, row: [{ id: 11, value: "x" }, { id: 12, value: "y" }, { id: 13, value: "z" }, ], }, { id: 2, row: [{ id: 21, value: "a" }, { id: 22, value: "b" }, { id: 23, value: "c" }, ], } ] function deleteByIndex(array, index1, index2) { array[index1]?.row?.splice(index2, 1) return array } console.log(deleteByIndex(array, 1, 2))