0

I have this large object that has the key 'visible' peppered throughout it. I use it to show/hide an item in the UI.

However, I have these buttons named 'Show All' / 'Collapse All' where I would like to change the value for the key 'visible' accordingly. So it shows/hides all the content at once.

The object looks something like this:

{
  toplevelkey: [
    {
      innerKey: someValue,
      visible: false
    },
    {
      innerKey: someValue,
      visible: false
    }
  ],
  visible: true
}

I tried using recursion to solve this, but it didn't really help.

Riza Khan
  • 2,712
  • 4
  • 18
  • 42

2 Answers2

1

Here's a recursive solution that uses a for...in to loop through all properties:

const a={toplevelkey:[{innerKey:"someValue",visible:!1},{innerKey:"someValue",visible:!1}],visible:!0};

function toggle(obj, show) {
  if (typeof obj == "object" && obj != null) {
    obj.visible = show;
    for (const key in obj) {
      toggle(obj[key], show);
    }
  }
}
toggle(a, true);
console.log(a);

Interactive demo:

const a={toplevelkey:[{innerKey:"someValue",visible:!1},{innerKey:"someValue",visible:!1}],visible:!0};

function toggle(obj, show) {
  if (typeof obj == "object" && obj != null) {
    obj.visible = show;
    for (const key in obj) {
      toggle(obj[key], show);
    }
  }
}

hide.addEventListener('click', ()=>{ toggle(a, false); console.log(a);})
show.addEventListener('click', ()=>{ toggle(a, true); console.log(a);})
<button id="hide">Hide All</button>
<button id="show">Show All</button>
Spectric
  • 30,714
  • 6
  • 20
  • 43
0

I thought it would be fun to do a straight search replace using string methods. This function will toggle all of your visible: true/false.

It can easily be adapted to set all to be one or the other, but for now it just toggles them. Enjoy!

let data = {
  toplevelkey: [{
      innerKey: 'someValue',
      visible: false,
      sub: {
        innerKey: 'someValue',
        visible: false
      }
    },
    {
      innerKey: 'someValue',
      visible: false
    }
  ],
  visible: true
}

const toggleBool = obj => JSON.parse(JSON.stringify(obj).replace(/visible\":[\w]+/g, function(m, o, s) {
  return `visible":${m.split(":")[1] === 'true' ? false : true}`
}))

console.log(toggleBool(data))
Kinglish
  • 23,358
  • 3
  • 22
  • 43