Search code examples
javascriptarraysreactjsreduceuse-reducer

How to separate a series of objects from the object


I'm using a useReducer And this is what I have:

const initialState = {
    optionalFilter: {
      take: Math.round((window.innerHeight - 330) / 34),
      page: 1,
    },
    reportFilter: {
      searchItem:[],
      dateFilter: {
        StartDate:new Date(new Date().setDate(new Date().getDate() - 3100)),
        EndDate:new Date(),
      },
     
    }, 
  };
const reducer = (state, action) => {
    switch (action.type) {
      case "changeFilter":
        console.log("action",action.payload)
        return updateObject(state, {
          optionalFilter: updateObject(state.optionalFilter, {
            page: 1,
          }),
          reportFilter: updateObject(state.reportFilter, {
            searchItem: action.payload,
          }),
          reportFilter: updateObject(state.reportFilter.dateFilter, {
            StartDate:new Date(new Date().setDate(new Date().getDate() - 3100)),
        EndDate:new Date(),
          }),
        });
    }
  };

When I want to apply filler .For example, when I get a console of action, I have such an array:

console of action.payload==>[{property:"StartDate: , value:"12.12.12"}{property:"EndDate: , value:"13.13.12"}{property:"Title: , value:"test"}{property:"name": , value:"name"}]

How should I have the StartDate and EndDate values in state.reportFilter.dateFilter And put the rest of the values in the searchItem array


Solution

  • Please try this code by replacing the reducer method

    const reducer = (state, action) => {
        switch (action.type) {
          case "changeFilter":
            console.log("action",action.payload)
            return updateObject(state, {
              optionalFilter: updateObject(state.optionalFilter, {
                page: 1,
              }),
              reportFilter: updateObject(state.reportFilter, {
                searchItem: action.payload.filter(val => val.property !== "StartDate" &&  val.property !== "EndDate");,
              }),
              reportFilter: updateObject(state.reportFilter.dateFilter, {
                StartDate:action.payload.find(val => val.property === "StartDate").value,
            EndDate:action.payload.find(val => val.property === "EndDate").value,
              }),
            });
        }
      };