1

I have an array of objects and each object has these values

 id: "53ed5e27-23a5-4a06-b53f-d0113d607fb5"
measure:
units: Array(2)
0: {perPortion: 15, name: "tbsp"}
1: {perPortion: 1, name: "ml"}

I am looping over the array and passing an on click function to a button.

function handleClick(index: number, ingredient: Data) {
    //copy original array
    const newListArr = [...props.data];

    newListArr[index] = {
        ...newListArr[index],
      }

}

The function is getting the index of the object clicked. I am copying the looped array and then I am trying to use the spread operator to bring in all the properties.

My problem is that I dont know how to use spread operator with nested objects.

I want to get only target the value of the "perPortion" key inside the units array without affecting anything else. How can i do that ?

Thank you in advance for the help!

1 Answer 1

1

I want to get only target the value of the "perPortion" key inside the units array without affecting anything else.

You can copy the entire nested object then overwrite values for specific keys. You will need to shallow copy all nested properties that are being updated.

function handleClick(index: number, ingredient: Data) {
  const newItem = {
    // shallow copy data
    ...props.data,
    measure: {
      // shallow copy measure object
      ...props.data.measure,
      // copy units array
      units: props.data.measure.units.map((unit, i) =>
        i === index
          ? {
              // shallow copy specific unit at matched index
              ...unit,
              perPortion: // new per portion value
            }
          : unit
      )
    }
  };

  .... // return or use newItem
}
Sign up to request clarification or add additional context in comments.

6 Comments

Thank you for your comment @Drew, I did that but the key PerPortion is just getting added to the whole object instead of getting overwritten
Ideally I would like to target only the "perPortion" key inside the first object units[0].perPortion
@Whyudodis That means perPortion property doesn't exist in array objects previously, to be overwritten. Can you share an example of your actual data, and what specifically you are trying to update a perPortion property of?
perPortion only exists inside "units" which is an array and "units" exists inside "measure" which is an object. Thank you very much for your time
@Whyudodis No worries. Can you share what the outer object is? Is it just an object or is it also part of some array? Is index in the handler the index of the nested units array you want to update?
|

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.