Home > Back-end >  Add key and value of object based on Array value
Add key and value of object based on Array value

Time:07-26

Iam working on a little project here, but i had some puzzle to do.

So i had a state of react the value is like this

const [dayValue, setDayValue] = useState({
    monday: false,
    tuesday: false,
    wednesday: false,
    thursday: false,
    friday: false,
    saturday: false,
    sunday: false,
  });

And then i had an array like this

const arrayDays = ['monday', 'wednesday', 'saturday'];

What i want to do is to make all of my key object value that has the same value in arrayDays to change the value become true

I already tried some methods, one of it is i implement it on useEffect like this

    for (const x=0; x<arrayDays.length; x  ) {
      for (const key in dayValue) {
        if (key === arrayDays[x]) {
          setDayValue({
            ...dayValue,
            [key]: true,
          });
          break;
        }
      }
    }

but its not working because setState hooks is a async function *CMIIW. does anyone know hot to solve this puzzle ?

CodePudding user response:

Set the state using the functional update argument:

setDayValue(dayValue => {
  const updated = {...dayValue};
  let needsUpdate = false;
  for (const day of arrayDays) {
    if (!(day in updated)) continue;
    updated[day] = true;
    needsUpdate = true;
  }
  return needsUpdate ? updated : dayValue;
});

CodePudding user response:

var temp = {...dayValue};
arrayDays.forEach( day => {
    if (temp[day] !== undefined) temp[day] = true;
})
setDayValue(temp);

CodePudding user response:

Always try to use immutable data structures when updating state in react. So this is what i would recommend

const arr = ['monday', 'wednesday', 'saturday'];

const updateDayValue = (arr) => {
  const updated = {
    ...dayValue,
    ...arr.reduce((acc, cur) => {
      return {
        ...acc,
        [cur]: true
      }
    }, {})
  }
  setDayValue(updated)
}

CodePudding user response:

I have written small piece of code for this one. I could have written one liner but I choose to split my logic in small pieces for you understanding

const updateState = () => {
    const stateClone = { ...dayValue };
    const keyValueMap = Object.keys(stateClone).map((key) => ({
      key,
      value: stateClone[key]
    }));
    const updatedState = keyValueMap.reduce(
      (acc, { key }) => ({ ...acc, [key]: arrayDays.includes(key) }),
      {}
    );
    setDayValue(updatedState);
  };

Also if you have any confusions you can go through this sandbox link: https://codesandbox.io/s/falling-wood-gflskr?file=/src/App.js:350-699

CodePudding user response:

arrayDays.map(i => {
  Object.keys(dayValue).map(n => {
    if(i === n){
      setDayValue(daysN => {
        let days = {...daysN}
        days[n] = true
        return days
      })
    }
  })
})
  • Related