Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
53 views
in Technique[技术] by (71.8m points)

javascript - Array inside object with store

I have this Redux store and reducer

const INITIAL_WORK = {
    departments: []
}
const works = (state = INITIal_WORK, action) => {
    switch(action.type){
        case 'ADD_DEPARTMENT':
            return {
                ...state,
                departments: [...state.department, action.item]
            }
        default:
            return state
    }
}

In departments work people so I want to this people was inside a single department works people. So after fetch data from db I want my store look like this:

const INITIAL_WORK = {
    departments: [
        {
            id: 1,
            name: "First department",
            people: [
                {
                    id: 1,
                    name: "Johna Wayne"
                },
                {
                    id: 2,
                    name: "Jessica Biel"
                },
                {
                    id: 3,
                    name: "Bratt Pitt"
                }
            ]
        },
        {
            id: 2,
            name: "second department",
            people: [
                {
                    id: 4,
                    name: "Salma Hayek"
                },
                {
                    id: 5,
                    name: "Sylvester Stallone"
                }
            ]
        }
    ]
}

Is it possible create case in reducer which will be added people inside people array inside single department? How can I do that?

question from:https://stackoverflow.com/questions/65859238/array-inside-object-with-store

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Yes, absolutely.

Let us assume your API returns payload as following.

{
 departmentId: `id of the department`
 id: `person id`
 name: `person name`
}

const INITIAL_WORK = {
    departments: []
}

const works = (state = INITIal_WORK, action) => {
    switch(action.type){
        case 'ADD_DEPARTMENT':
            return {
                ...state,
                departments: [...state.department, action.item]
            }

        case 'ADD_PERSON':
            const { departmentId, id, name } = action.item
            const departments = [...state.departments];

            departments[departmentId].people.push({id, name})
            return {
                 ...state,
                 departments
            }

        default:
            return state
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...