0

My question is just one step ahead of question here

I want to know if there is any way by which I can use variables in place of "Professional" (which is a key in reference question) because my model is of the following type:

const list = {
  categories: {
    1: {
      name: "Golf",
      active: false
    },
    2: {
      name: "Ultimate Frisbee",
      active: false
    }
  }
}

I want to access 1 and 2 i.e. ids in the code below:

return {
  ...state,
  categories: {
    ...state.categories,
    <dynamic_Id>: {
      name:"xyz"
    }
  }
}

My main aim is to update name property of selected id. Please let me know if there is any solution to it. Thanks in advance.

Vinita
  • 117
  • 8

2 Answers2

3

I think this is what you're after

  return {
      ...state,
      categories: {
        ...state.categories,
        [idProp]: {
        ...state.categories[idProp],
          name:"xyz"
        }
      }
    }
MistyK
  • 6,055
  • 2
  • 42
  • 76
  • what is 'idProp' over here? – Vinita Jun 27 '18 at 09:17
  • I got it. 'idProp' is a variable in which the id that is to be changed is assigned. The main thing here is the syntax which I was not able to find. That square brackets [] are necessary. that solved my problem. Thanks a lot. – Vinita Jun 27 '18 at 09:40
1

So Finally My solution is as follows:

let idProp = 1;
return {
      ...state,
      categories: {
        ...state.categories,
        [idProp]: {
        ...state.categories[idProp],
          name:"xyz"
        }
      }
    }
Vinita
  • 117
  • 8