Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unused property dropped?

First things fist, my class:

export class FooBar {
 ...
 isFavorite: boolean = false;

 constructor() {
   this.isFavorite = false;
  }
}

Using Lodash I sort a list of FooBar, so my favorites would be on top of the list:

this.fooBars = _.orderBy(this.fooBars, ['isFavorite', 'name'], ['desc', 'asc']);

When I favorite an item and look at my console.log it states this:

isFavorite is not shown when false

Note that #3 does not have the isFavorite property...

Whenever I never set isFavorite it's not shown. This makes Lodash sort in a wrongly matter.
Is there a way to always show this property, even when it's unused/unset/false?

I tried:
- Setting the property to false in the class
- Setting the property to false in the constructor of the class
- Looping over this.foobars in my component, setting them all to false
- Adding an interface to FooBar

like image 571
Hypenate Avatar asked Nov 07 '22 04:11

Hypenate


1 Answers

I think that's the typeScript way to default a class propriety

export default class FooBar {
  constructor(private isFavorite: boolean = false) {
     ...
  }
}

or simply

export class FooBar {
  constructor() {
     this.isFavorite = false;
  }
}

Or you could use a function in the _.orderBy iteratee to sort your list accordingly:

var foobars = [{isFavorite:false, name:"aaa"}, {isFavorite:true, name:"bbb"}, {isFavorite:false, name:"ccc"}, {name:"ddd"}]


foobars = _.orderBy(foobars, [function(foobar) {
    return foobar.isFavorite == true;
}, "name"], ["desc", "asc"]);

console.log(foobars)
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
like image 123
Below the Radar Avatar answered Nov 15 '22 07:11

Below the Radar