0

How do I toggle the status of an object based on checked or unchecked. Here newState[id] = !newState[id] works with 1st level objects. But if the objects are nested it doesn't work.

So, I am trying to use the key property if (id == 'z.aa') newState.z.aa = !newState.z.aa;. However, if there are 100 nested objects, this approach will not be feasible.

Please help me with this toggle of nested objects. Thanks.!

const function App() {
  let [state, setState] = useState({
    a: false,
    z: { aa: false, bb: false },
  });

  const handler = (e) => {
    let id = e.target.id;
    let newState = JSON.parse(JSON.stringify(state));
    if (id == 'z.aa') newState.z.aa = !newState.z.aa;
    else if (id == 'z.bb') newState.z.bb = !newState.z.bb;
    else newState[id] = !newState[id];
    setState(newState);
  };
  return (
    <div onClick={(e) => handler(e)}>
      <input type="checkbox" id="a" checked={state.a} />
      all
      <input type="checkbox" id="z.aa" checked={state.z.aa} />A
      <input type="checkbox" id="z.bb" checked={state.z.bb} />B
    </div>
  );
}

1 Answer 1

1

I think you can try Lodash .get and .set method

_.set(newState, id, !_.get(newState, id));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.