Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngrx update object inside array

I have a ngrx store with array of objects. What I am looking for is, update(modify) the object inside the array using the array index. My ngrx data will look like,

    policies: {
        beneficiaries: {
            beneficiaries: [{
                    name: 'pqr'
                    age: 56
                },
                {
                    name: 'xyz'
                    age: 76
                }
            ]
        }
    }

I have to update the beneficiary name based on the array index. So I have implemented the following reducer function

    on(policiesActions.updateBeneficiaryPercentage, (state, action) => {
        return {
          ...state,
          beneficiaries: {
            ...state.beneficiaries,
            beneficiaries: {
              ...state.beneficiaries.beneficiaries,
              [action.index]: {
                ...state.beneficiaries.beneficiaries[action.index],
                name: action.value
              }
            }
          }
        };
      })

The issue with the above code is that after running this code the structure of my store is changing to

policies: {
    beneficiaries: {
        beneficiaries: {
            0: {
                name: 'pqr'
                age: 1000
            },
            1: {
                name: 'xyz'
                age: 76
            }
        }
    }
}

Please help me to fix the code so that I can update the value without altering the store structure.

like image 410
Jobz Avatar asked May 02 '20 18:05

Jobz


1 Answers

Use the Array.map method:

arr.map((value, index) => index === action.index ? {...value, name: action.value} : value) 

Or just use ngrx-etc, which lets you mutate your state in a mutable way while remaining immutable

mutableOn(onAction, (state, action) => {
  state.arr[action.index].name = action.name
  return state
})
like image 158
timdeschryver Avatar answered Oct 30 '22 02:10

timdeschryver