简体   繁体   中英

Structuring of Redux state objects

I am new to redux,And I am quite stuck while designing the shape of the redux state.My current part of redux state looks like this

Invite reducer:

invitees: [{
    '_id': '626262',
    'name': 'xyz'
}, {
    '_id': '6262',
    'name': 'jsjsj'
}, {
    '_id': '626',
    'name': 'gdgdg'
}
....
]

Should I keep this object like this or should I keep out the id's and make that as a key like:

invitees: [626262: {
    'name': 'xyz'
}, 6262: {
    'name': 'jsjsj'
}....]

If I have to go with the second option,how can I do this?? I have read in few blogs which says second option would be helpful.

You can transform your array of responses to what you want by using Reduce and Object Spread Operator

const data = [
    { id: 1, name: 'name-1' },
    { id: 2, name: 'name-2' },
    { id: 3, name: 'name-3' },
    { id: 4, name: 'name-4' },
    { id: 5, name: 'name-5' }
];

function myReducer({ payload }) {
    return payload.reduce((acc, current) => {
        return Object.assign({}, acc, {
            [current.id]: {
                [current.name]: current.name
            }
        })
    }, {});
}


const newState = myReducer({ payload: data });

console.log(newState);
/**
{
   1: { name: 'name-1' }
   2: { name: 'name-2' }
   3: { name: 'name-3' }
   4: { name: 'name-4' }
   5: { name: 'name-5' }
}
*/

You second example is not a valid javascript object. What you need in the second example is not an array but rather an object like

invitees: {
    '626262': {
       'name': 'xyz'
    }, 
    '6262': {
       'name': 'jsjsj'
    }
    ....
}

The second exmaple helps you in a sense that in order to get a name attribute you don't have to loop though each and every element of the array to search for the id rather you can direclty access it with the brackets notation

Example

return Object.assign({}, state, {
    [id]: {
        name: 'abc'
    }
})

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