1

I'm building a calorie counting application using React. One of my components has in its state a list of food items:

this.state = {
   items: [
      {
        name: 'Chicken',
        selectedServing: {
           label: 'breast, grilled',
           quantity: 3
        }
      },
      {
        name: 'French Fries',
        selectedServing: {
           label: 'medium container',
           quantity: 1
        }
      }
   ]

When a user changes the serving size they consumed, I have to update the properties of the item in the items[] array. For example, if a user ate another chicken breast, I'd need to change the selectedServing object in items[0].

Since this array is part of the component's state, I'm using immutability-helper. I've found that I can properly clone and mutate the state in this way:

let newState = update(this.state, {
  items: {
    0: {
      selectedServing: {
        servingSize: {$set: newServingSize}
      }
    }
  }
});

The above code sets the servingSize for the first element in the items[] array, which is Chicken. However, I won't know the index of the object I need to update beforehand, so the 0 I hardcoded won't work. It seems that I can't store this index in a variable, because update() will think it's an object key.

How can I programmatically update an object at a specific index in a list?

2
  • you don't know the index that you want to update? Do you not have the it as a variable? Commented Apr 28, 2018 at 17:29
  • @riwu I do have it as a variable, but I'm unable to use it because the update method recognizes it as an object key. Commented Apr 28, 2018 at 17:37

1 Answer 1

2

An variable can be used as a key of an object.

let foo = 3
let newState = { items: { [foo]: { somthing: 'newValue' } } }
// above is equal to { items: { '3': { somthing: 'newValue' } } }

You can find the index number of 'Chicken' and save it into an variable, and use it to composit newState.

Sign up to request clarification or add additional context in comments.

Comments

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.