0

I have this appointments object that has three keyed arrays. I'm trying to find a clean JS way to check the truthiness for a v-if when all three block arrays are empty a la:

{ 
    "block_1": [], 
    "block_2": [], 
    "block_3": [] 
} 

I have been trying to use Object.values(). For example, this code will return true if all the arrays are truthy and false if even one of them is empty:

Object.values(appointments).every(item => item.length)
Matt Larsuma
  • 1,456
  • 4
  • 20
  • 52

1 Answers1

1

Make a computed property:

hasAppointment() {
  return !!Object.values(this.appointments).find(i => i.length);
}

And then use that computed in your v-if statement:

<div v-if="hasAppointment"></div>
thanksd
  • 54,176
  • 22
  • 157
  • 150
  • That is always returning false. – Matt Larsuma Sep 06 '18 at 17:19
  • It shouldn't be. Although I made some small assumptions about your Vue component since you didn't share it. [Here's a full fiddle example.](https://jsfiddle.net/rcg61fLv/1/) – thanksd Sep 06 '18 at 17:26
  • Yeah, that totally works right. The issue is that when the data comes in it's an object of objects, rather than an object of arrays: `{ block_1: {"foo": "foo"}, block_2: [], block_3: [] }` – Matt Larsuma Sep 06 '18 at 17:37
  • So... this works: `return !!Object.values(this.appointments).find(i => Object.keys(i).length)`. Anyways, thanks! My bad for leaving that part out. – Matt Larsuma Sep 06 '18 at 17:39
  • Is there a reason that you initialize the data as arrays? Because if not, you should just initialize them to `null` and you could use `.find(i => i)` instead. – thanksd Sep 06 '18 at 17:40
  • 1
    It's some weird old-school dev's backend php stuff that I cannot change at the moment, so I'm just working with it the best I can. It's totally necessary. Could've just been json. The block numbers are in the nested objects. He just likes to key everything extraneously. – Matt Larsuma Sep 06 '18 at 17:48