Editing object inside an object in an array of objects

I have the following two types:

export default interface ImageDataForAnnotation {
    src: string;
    name: string;
    key: number;
    regions?: Annotation[]; //This is defined below
    pixelSize?: PixelSize
}


export interface Annotation {
    type: string,
    x: number,
    y: number,
    w: number,
    h: number,
    highlighted: boolean,
    editingLabels: boolean,
    color: string,
    cls: string | undefined,
    id: number,
    image?: number,

}

Then i have an array where each image holds a number of annotations

  const [images, addImage] = useState<Array<ImageDataForAnnotation>>([]);
  
  //Definition of arary

  let imageArray = [...images];

I then want to edit an annotation in a given image, where i have both indexes to do something like: imageArray[image_index].regions![annotation_index].update(new_annotation)

1 answer

  • answered 2022-05-04 13:04 jsN00b

    I would firstly rename the method as addImage is misleading because the method may be used to edit/update, or even remove/delete items from images array.

    So, firstly:

     const [images, setImages] = useState<Array<ImageDataForAnnotation>>([]);
    

    Next, let us assume the index are available at variables named: imageIndex and annotationIndex (again, CamelCase is my preference) and the value that needs to be used is at newAnnotation, then to update the corresponding item within the state-variable images, here's what I would do:

    setImages(prev => {
      const curr = [...prev];
      curr?.[imageIndex]?.regions?.[annotationIndex] = newAnnotation;
      return curr;
    });
    

    Use the callback function to access the previous-state of images and then update the specific item and return the updated version. I've used a shallow-copy curr for better readability & it's not necessary.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum