Maddy
Maddy

Reputation: 2060

Making a new array after destructuring items and destructuring behavior

I am returning an observable from a service and I want to create a new array;

stackblitz code here

allCodesAndIds: Option[] = [];

service call

  getAllItems(): Observable<Item> {
    return of(this.jsonData);
  }

destructuring items the following way

  getAllItems() {
    const items$ = this.service.getAllItems();
    items$.pipe().subscribe(res => {
      const [id, code] = res.items;
      console.log(id, code);
    });
  }

I want my allCodesAndIds array to look like the following

[
  {
    id: 1,
    descp: "item 1"
  },
  {
    id: 2,
    descp: "item 2"
  },
  {
    id: 3,
    descp: "item 3"
  },
  {
    id: 4,
    descp: "item 4"
  },
  {
    id: 5,
    descp: "item 5"
  }
]

Also, the current console.log only prints 2 items

{id: 1, descp: "item 1", code: "code1"}
{id: 2, descp: "item 2", code: "code2"}

whereas I was expecting it to return all 5 items. Could someone please explain the reason behind this. Please.

Thank you for your time and help !!

Upvotes: 0

Views: 335

Answers (1)

code-gorilla
code-gorilla

Reputation: 2418

If I understand you correctly, you want to destructure your items like this:

const items = res.items.map(({id, descp}) => ({id, descp});

This is called object destructuring.

In your snippet, you are not using object destructuring but array destructuring. This takes the first and second item from your list of items.

const [item1, item2] = res.items;

Array destructuring has its use cases, too, e.g. separating head and tail of a list, useful for recursive algorithms:

const [first, ...rest] = res.items;

Upvotes: 3

Related Questions