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:
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
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With