0

I am trying to update a deeply nested json property and I am not able to do so. I have tried several ways, anyone have any thoughts?

Way 1: doesn't work...

case ADD_REWARD:
  console.log("state", state);
  console.log("reward index", action.index);
  return {
    ...state,
    rewards: [
      {
        ...state.rewards[action.index],
        value: {
          ...state.rewards[action.index].value[0],

          target: [
            ...state.rewards[action.index].value[0].target,
            initialState.value_key_pair
          ]
        }
      }
    ]
  };

Way 2: works, except it adds index to object which isn't desired...

case ADD_REWARD:
  console.log("state", state);
  console.log("reward index", action.index);
  return {
    ...state,
    rewards: [
      {
        ...state.rewards,
        [action.index]: {
          ...state.rewards[action.index],
          value: {
            ...state.rewards[action.index].value,
            [0]: {
              ...state.rewards[action.index].value[0],
              target: [
                ...state.rewards[action.index].value[0].target,
                initialState.value_key_pair
              ]
            }
          }
        }
      }
    ]
  };

What I want this state to look like after immutably updating.

    rewards: [
      {
        type: "group",
        operand: "AND",
        value: [
          {
            type: "discount",
            subtype: "percent",
            value: 20,
            target: [
              {
                type: "abc",
                value: "123"
              },
              {
                type: "def",
                value: "456"
              }
            ]
          }
        ]
      }
    ]
Tomasz Mularczyk
  • 34,501
  • 19
  • 112
  • 166

1 Answers1

0

Here's what I came up with after a bit of discovery.

 return {
            ...state,
            rewards: state.rewards.map((group,index) => index === action.index ?
                // transform the one with a matching id
                { ...group, value: [...group.value.map((reward, index) => index === 0 ?{
                    ...reward,
                        target: [...reward.target, initialState.value_key_pair]
                } :reward
                )]
                } : group
            ),
        }