Home > Net >  Convert object to boolean in JavaScript
Convert object to boolean in JavaScript

Time:09-05

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
          
          (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

CodePudding user response:

It is because you are trying to print an object in the template. Also, the bookmarked value is a string(a non-empty string is always true), not a boolean change it to boolean.

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

create a function convert string to the boolean method in util:

const stringToBoolean = key => key === 'true' ? true: false;

You don't need to make changes to your template.

CodePudding user response:

It looks like bookmarked is an object property and not an object or variable.

So, you need to use object_name.bookmarked like this inorder to work.

OR

You can destructure the object like this.

const {bookmarked} = apiResponseData;

Now you can use bookmarked.

  • Related