Home > Net >  How to remove dynamic key from useState object in React?
How to remove dynamic key from useState object in React?

Time:07-07

How can I remove dynamic key and it's value from react useState object?

I have a checkedItems object. Based on the function call I want to remove the dynamic key and it's value from the object:

  const [checkedItems, setCheckedItems] = useState(null)

    const unCheckItem =(item) => {
    const {id} = item
    setCheckedItems(prevState) => ({
    ...prevState
    // How should I remove that dynamic key which has the value of id?
    })
    }

How can I remove the dynamic key which has the value of id and also remove it's value?

CodePudding user response:

You can create helper to remove key and use it on previous state, like this:

const removeKey = (key, { [key]: _, ...rest }) => rest;
...
...
setCheckedItems(prev => removeKey(id, prev));

CodePudding user response:

you can use this way, it will work 100%!

    let newObject = {};
    for (let [key, value] of Object.entries(checkedItems)) {
        if (key != id) {
            newObject[key] = value;
        }
    }
    setCheckedItems(newObject);
  • Related