0

I have an array of objects and when my component mounts I want to modify a property on the objects in the array.

For context: I am loading a component, waiting for the images to load, then i get the image dimensions and then i figure out the aspect ratio and change that value in the array.

Here is some reduced code for readability:

let itemsOriginal = [
  {
    id: 1, 
    src: "<img-src>",
    aspectRatio: null
  },
  {
    id: 2, 
    src: "<img-src>",
    aspectRatio: null
  },
  {
    id: 3, 
    src: "<img-src>",
    aspectRatio: null
  }
];

const [items, setArr] = useState(itemsOriginal);

useEffect(() => {
  
  // figure out aspect ratio
  // then try and set that value to obj property in array

  setArr(
    items.map((item, index) => {
      item.aspectRatio === null 
        ? {...item, aspectRatio: "changed"} // <<< how do i get item.aspectRatio to update ???
      : '' 
    }
  ))
})

1 Answer 1

2

You can do,

  const update = () => {
    const itemsClone = [...items];
    itemsClone.forEach((p) => {
      p.aspectRatio = 'new value';
    });
    setArr(itemsClone);
  };
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Anoop, I ended up using a map as I wanted to filter which item properties get changed, but this syntax is exactly what I was looking for, thanks again :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.