Why wont the second if condition execute

Viewed 41

I have the following data

[
  {
    "itemType": "HEADER",
    "createdBy": "Jake",
    "deliveredBy": "Paul",
  },
  {
    "itemType": "HEADER_DATA",
    "createdBy": "Ryan",
    "deliveredBy": "Blair",
  },
  {
    "itemType": "HEADER_DATA",
    "createdBy": "John",
    "deliveredBy": "Doe",
  },
  {
    "itemType": "HEADER_DATA",
    "createdBy": "Sally",
    "deliveredBy": "Hansen",
  }
]

I want to separate out the items by the item type

  test(itemType: string) {
    this.service
      .getData(itemType)
      .pipe()
      .subscribe(([{itemType, createdBy, deliveredBy}]) => {
        if (itemType === 'HEADER') {
          console.log('1');
        }
        else if (itemType === 'HEADER_DATA') {
          console.log('2');
        }
      });
  }

The console never reaches 2. I know this is a simple logic issue but I have been at it for a while and cannot seem to figure it out.

Thank you for your time and help

Stackblitz here

1 Answers

because you receive an array at subscribe and you are destructuring the first element of that array only. if you want to log each one you can change to:

data.pipe().subscribe((arr) => {
  arr.forEach(({itemType, createdBy, deliveredBy}) => {
  if (itemType === "HEADER") {
    console.log("1");
  } else if (itemType === "HEADER_DATA") {
    console.log("2");
  }
 })
});
Related