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"
              }
            ]
          }
        ]
      }
    ]
2
  • why not using map and check the index, for specific index return the updated data otherwise same. Check this answer. Commented Mar 21, 2018 at 15:15
  • thanks @MayankShukla I figured it out! Commented Mar 22, 2018 at 16:33

1 Answer 1

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
            ),
        }
Sign up to request clarification or add additional context in comments.

1 Comment

you don't need this: [...group, you can directly write: value: group.value.map(.....)

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.