Is the neglected property being discarded?

First things first, let's talk about my class:

class FavoriteFooBar {
 ...
 isPreferred: boolean = false;

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

Using a utility library called Uniquer, I arrange a list of FavoriteFooBar instances to prioritize favorites at the top:

this.favFBBars = Uniquer.orderBy(this.favFBBars, ['isPreferred', 'name'], ['desc', 'asc']);

After marking an item as favorite and checking my console log, it shows:

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

It seems like Lodash doesn't sort properly when isPreferred isn't explicitly set. Is there a way to always display this property, even if it's unused/unset/false?

I've already tried:
- Initializing the property to false in the class
- Setting the property to false in the constructor of the class
- Iterating through this.favFBbars in the component and setting them all to false
- Implementing an interface for FavoriteFooBar

Answer №1

It appears that this is the TypeScript approach to setting a default value for a class property.

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

Alternatively, you can achieve the same result with the following code:

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

If you want to sort a list based on a specific condition, you can use a function in the _.orderBy iteratee like this:

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/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aec2c1cacfddc6ee9a809f99809f9e">[email protected]</a>/lodash.min.js"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the most efficient way to print multiple JSON arrays simultaneously?

When looping through a database using an array, the following code snippet is used: $checkedProducts = $request->input('products'); $p = null; foreach($checkedProducts as $checkedProduct){ $p .= DB::table('products')->where( ...

What is the best way to trigger a jQuery UI dialog using an AJAX request?

My website includes a jQuery UI Dialog that opens a new window when I click the "create new user" button. Is there a way to open this window using an AJAX request? It would be useful if I could open the dialog-form from another page, such as dialog.html ...

Acquiring a fresh scope in Angular via a different component

In my project, I am developing an app using a component-based approach with Angular 1.5.5. As part of this development, I am utilizing d3js to create some elements with the class .floating-node. For each of these nodes, I am creating a new $scope and appe ...

What could be the reason for my image not loading properly in Vue.js 3?

I'm struggling to load an image using a relative path and value binding with v-for in my template code. Despite following the correct syntax, the website is displaying an error indicating that it can't retrieve the image. Here's a snippet of ...

Issue with AngularJS: Component controller fails to load upon routing using ngRoute

As a newcomer to AngularJS, I am struggling with the following code snippet: This is the component defined in the JavaScript file provided: angular.module('EasyDocsUBBApp') .component('loginTag', { templateUrl: 'login ...

Having trouble retrieving specific data with curl

Trying to retrieve specific data using cURL from the website . The following code is used to fetch all data: <?php $url='http://dummy.restapiexample.com/api/v1/employees'; $my_curl = curl_init(); curl_setopt($my_curl, CURLOPT_URL, $url); curl ...

What is the best way to acquire the href value from this source?

Looking to extract the dynamic value "3 Sent" from the html snippet provided. How can this be achieved? <ul class="nav nav-tabs some-tabs"> <li class="active"> <a href="#accepted" data-toggle="tab">1 Accepted</ ...

What are the steps to execute PhantomJS on a client machine?

I have implemented an HTML to PDF converter that utilizes phantomjs, following this method: npm install -g html-pdf var fs = require('fs'); var pdf = require('html-pdf'); var html = fs.readFileSync('./test/businesscard.html' ...

Ways to adjust a specific div within an ng repeat using the value from JSON in AngularJS

When I select a different option from the dropdown menu, such as cities or states, the values are populated from a JSON file. My specific requirement is to hide a button only when the value 'No data' is populated upon changing the dropdown select ...

Query in JSONPath to retrieve elements in an array depending on a specified key's value

I am working with a JSON Array that contains multiple JSON objects: [ { "s3_uri":"s3://fake-s3-bucket/fact_table/fact_table.csv", "dataset":"fact_table" }, { "s3_uri":"s3://f ...

Instructions for utilizing ObjectId with a string _id on the client side

Is there a way to retrieve a document using the _id in string format? Here is an example of the code on the client side: 'use client' ... const Page(){ ... fetch("api/get_data", { method: 'POST', ...

Next.js does not support tooltips with custom children components

I created a unique Tooltip component and I'm attempting to include NextLink as the children. However, I encountered an error similar to the one below. Warning: Failed prop type: Invalid prop `children` supplied to `ForwardRef(Tooltip)`. Expected an e ...

Conceal component while navigating in VueJs

I am working on a Vue project. I am trying to implement a feature where a component is hidden while the user scrolls, but then reappears once the scrolling stops. I have tried using a scroll event, but the component does not show up again. <div c ...

The Intersection Observer API is not compatible with using transform: translateX()

After successfully implementing the Intersection Observer API on my website and incorporating a few transitions from an example I came across, everything seemed to be working smoothly. You can view the scale-in transition in action here: https://jsfiddle.n ...

How One Simple Click Can Impact Every Button in jQuery Ajax操作

Whenever I try to click a button that should only affect a specific id, it ends up affecting every button on the page by sending data to our API as well. You can check out a snapshot of my page here. Each row has a unique id, but when I click the vote butt ...

Python JSON - Unable to read data due to TypeError: indices in string must be integers

Having trouble reading a JSON file I created in my script. When trying to access one of its "attributes" after reading it, the following error message pops up: Traceback (most recent call last): File "index.py", line 74, in <module> ...

Utilize typehead.js in Python Django to retrieve an updated data list directly from the database

file.js var source = new Bloodhound({ hint: false, datumTokenizer: Bloodhound.tokenizers.obj.whitespace("description"), queryTokenizer: Bloodhound.tokenizers.whitespace, // /a_c/p_s/?term=d&category=all remote: "/a ...

Comparison Between React-Redux mapStateToProps and Inheriting Props from ParentsIn the

Excuse my lack of experience, but I am currently delving into the world of react-redux and trying to grasp the concepts as I progress. Situation: In my main component within a react-redux application, I have the following snippet at the end: function map ...

Developing a fresh feature in Angular.js for transmitting my localstorage model information to a bus?

As a beginner in Angular Js, I have mastered the basics and am now working on storing user input values to localstorage using a form. Although this part is working fine, I need assistance in creating a new service to communicate with my colleague's . ...

Adding a new key/value pair to a nested object in Aerospike

Is there a way to add a new key/value pair in a nested object stored in bins of type map in Aerospike? For example, let's say I have the following key/value pairs stored in bins of type map: { "a" : "apple", "b" : "ball", "c" : { "d" : "dog", ...