Home > Back-end >  Toggle Boolean status of Nested Objects: JavaScript
Toggle Boolean status of Nested Objects: JavaScript

Time:11-07

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>
  );
}

CodePudding user response:

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

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

  • Related