简体   繁体   中英

How to pass values of an array across properties of different array objects

  1. List item

I have a redux store with this structure

const INITIAL_STATE = {
    currentData: [
        {
            title: 'Total Insurance Bought',
            img: 'insurance-bought.svg',
            bg: 'insurance-shield',
            data: '',
        },
        {
            title: 'Total Amount of Claims',
            img: 'amount of claims icon.svg',
            bg: 'amount-of-claims',
            data: '',
        }
    ]
} 

This is the current structure of my reducer function

const summaryReducer = (state = INITIAL_STATE, action ) => {
    switch(action.type){
        case 'SET_SUMMARY_DATA':
            return {
                ...state,
                currentData: {
                    ...state.currentData,
                    data: action.payload
                }
            }
        default: 
            return state
    }
}

I would like to spread the values of this array in the action.payload, into each data property of the initial state while returning the whole state.

[ 0 , 20000 ]

I want my output to be

const INITIAL_STATE = {
    currentData: [
        {
            title: 'Total Insurance Bought',
            img: 'insurance-bought.svg',
            bg: 'insurance-shield',
            data: '0',
        },
        {
            title: 'Total Amount of Claims',
            img: 'amount of claims icon.svg',
            bg: 'amount-of-claims',
            data: '20000',
        }
    ]
} 

If your current data is always going to have two array items and if expected payload is going to have two elements in expected order, you can do it this way.

case 'SET_SUMMARY_DATA':
  return {
     ...state,
     currentData: currentData.map((currentItem, index) => {
       currentItem.data = action.payload[index];
       return currentItem;
     })
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM