Convert object to boolean in JavaScript

Discussão em 'Angular' iniciado por devZ, Janeiro 24, 2025.

  1. devZ

    devZ Guest

    The API returns me values like:

    {bookmarked: 'false'}


    or

    {bookmarked: 'true'}


    The code is:

    addToBookmark(): void {
    if (this.bookmarked) {
    this.bookmarkSubs = this.bookmarksService
    .removeFromBookmark(this.id)
    .subscribe((bookmarked: boolean) => {
    this.bookmarked = bookmarked;
    console.log(this.bookmarked);
    });
    } else {
    this.bookmarkSubs = this.bookmarksService
    .addToBookmark(this.id)
    .subscribe((bookmarked: boolean) => {
    this.bookmarked = bookmarked;
    console.log(this.bookmarked);
    });
    }
    }


    When I show the bookmarked value in the page (just for testing purposes) like {{ bookmarked }} the value is [object Object]

    I need to display 2 different icons based of the values true or false.

    HTML code:

    <button
    class="btn btn-trans tooltip bookmark"
    (click)="addToBookmark()"
    >
    Bookmark
    <fa-icon [icon]="faBookmarkRegular" *ngIf="!bookmarked"></fa-icon>
    <fa-icon [icon]="faBookmarkSolid" *ngIf="bookmarked"></fa-icon>
    </button>


    I can't directly get true or false from the bookmarked value from API, because it is an object. How can I transform this object to true or false, so I can show the right icons in the web page?

    Thanks to everyone

    Continue reading...

Compartilhe esta Página