digamos que tenemos:
let array_of_objects = [ { "color": "purple", "type": "minivan", "id": this.object.index // i know this is not valid code,but can this somehow get its own index within the array as value ? }, { "color": "red", "type": "station wagon", "id": this.object.index //this should be 1 } ]Pregunta real en los comentarios del código ... lo que estoy tratando de hacer es completar las entradas de un formulario usando un objeto, y quiero poder mostrar el índice real del objeto dentro de la matriz en una de las entradas
en lugar de usar el índice como identificación, sugiero crear una identificación compleja o puede usar la biblioteca uuid() para crear una identificación de usuario única uuid npm
import { v4 as uuidv4 } from 'uuid'; array_of_objects = array_of_objects.map((item, index) => ({ id: uuidv4(), ...item})) console.log(array_of_objects); let array_of_objects = [ { "color": "purple", "type": "minivan" }, { "color": "red", "type": "station wagon" } ]; array_of_objects = array_of_objects.map((item, index) => ({ id: index, ...item})) console.log(array_of_objects);Simplemente inicialice la matriz sin la identificación y agréguela luego usando un bucle for.
let array_of_objects = [ { "color": "purple", "type": "minivan", }, { "color": "red", "type": "station wagon", } ] for (let i = 0; i < array_of_objects.length; i++) { array_of_objects[i].id = i; }