简体   繁体   中英

How to push object inside the array using setState reactjs?

My State in Class Component

The below given state is in my class component.

I Need to add following example dynamic objects inside the starttime Array.

this.state = {
   frequency: {
       starttime: [],
   },
};

example objects which are given below.

{time:"20:15",timezone:"IST"},
{time:"01:30",timezone:"UST"}

The above objects were comes dynamically that I handled it.

My requirement is have to push these object in the starttime Array using setState in reactjs.

expected result as below.

this.state = {
   frequency: {
      starttime: [{time:"20:15",timezone:"IST"},
         {time:"01:30",timezone:"UST"},
         {time:"13:00",timezone:"UST"},...],
      },
};

Consider you have the data in a variable called newTimes that need to be updated as starttime in the state. Then below is one of the ways you can update it. You can refer here for more details about how previous state can be used while updating.

let newTimes = [{time:"20:15",timezone:"IST"}, {time:"01:30",timezone:"UST"}];
this.setState(state => ({
  ...state,
  frequency: {
    starttime: [...state.frequency.starttime, ...newTimes]
  }
}))

If you want to remove certain elements from the newTimes array based on on a condition, then Array.filter will be handy. For simplicity I'm considering to filter out the data based on timezone , below is the example

let newTimes = [{time:"20:15",timezone:"IST"}, {time:"01:30",timezone:"UST"}, {time:"16:45",timezone:"GMT"}];
//Removing all the timezones which are of "UST".
//You can change this condition as per your requirement.
const filteredTimes = newTimes.filter(({ timezone }) => timezone !== "UST");
this.setState(state => ({
  ...state,
  frequency: {
    starttime: [...state.frequency.starttime, ...filteredTimes]
  }
}))

There are different ways of removing duplicates from an array, please refer below

 let newTimes = [{time:"20:15",timezone:"IST"}, {time:"01:30",timezone:"UST"}, {time:"16:45",timezone:"GMT"}, {time:"20:15",timezone:"IST"},{time:"20:15",timezone:"PST"},{time:"12:30",timezone:"IST"}]; const removeDuplicates = (times) => { const finalRes = times.reduce((res, timeObj) => { const { time, timezone } = timeObj; const key = `${time}_${timezone}`; //Check if either the time or timezone are not same with any property from the result object. //If either of them is not matching, then add it to the res object if(res[key]?.time !== timeObj.time || res[key]?.timezone !== timeObj.timezone) { res[key] = {...timeObj} } return res; }, {}); //Finally return the values of the object by converting it to an array. return Object.values(finalRes); } console.log(removeDuplicates(newTimes))
 .as-console-wrapper { max-height: 100% !important; }

  • Using Array.filter

 let newTimes = [{time:"20:15",timezone:"IST"}, {time:"01:30",timezone:"UST"}, {time:"16:45",timezone:"GMT"}, {time:"20:15",timezone:"IST"},{time:"20:15",timezone:"PST"},{time:"12:30",timezone:"IST"}]; const removeDuplicates = (times) => { let obj = {}; return times.filter(timeObj => { const {time, timezone} = timeObj; const key = `${time}_${timezone}`; //Check if the formatted key is already present in the `obj`, if so return false else add the key and then return true. return obj[key] ? false: (obj[key] = true, true) }); } console.log(removeDuplicates(newTimes))
 .as-console-wrapper { max-height: 100% !important; }

Just combine last object state with new aray of times using spread operator

see example below :

let times = [];
times.push({time:"20:15",timezone:"IST"},{time:"01:30",timezone:"UST"});



this.setState({
   ...this.state, // spread here to prevent removing other key object if present
   frequency: {
     starttime : [...this.state.frequency.starttime, ...times] // merge previous value with new array
   }
})

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