0

I want to toggle the Boolean value of this nested input object

var obj = { a: { b: { c: false } } }; 

in an efficient way so that obj is output as:

{ a: { b: { c: true } } }; 

I am using:

Object.keys(obj).map(function(k, i) {
    // Check if obj is Boolean else if object nest again till I find the Boolean value and toggle it.
}
Ivar
  • 6,138
  • 12
  • 49
  • 61
RRR
  • 326
  • 2
  • 13
  • Does this answer your question? [Traverse all the Nodes of a JSON Object Tree with JavaScript](https://stackoverflow.com/questions/722668/traverse-all-the-nodes-of-a-json-object-tree-with-javascript) – xdeepakv May 19 '20 at 11:38
  • 3
    I suspect your question is leaving out details we need in order to help you. The literal answer is `obj.a.b.c = true`, but ... ? – T.J. Crowder May 19 '20 at 11:38

1 Answers1

2

You could build a new opbject and take either an object with a recursive call or a value and return the toggled value.

const
    toggle = object => Object.fromEntries(Object
        .entries(object)
        .map(([k, v]) => [k, v && typeof v === 'object' ? toggle(v) : !v])
    );

var object = { a: { b: { c: false } } };

console.log(toggle(object));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392