MarrZZ
MarrZZ

Reputation: 11

ngx dropdown list get selected values

I am trying to use ngx dropdown list like this:

<ngx-dropdown-list [items]="categoryItems" id="categoriesofdata" [multiSelection]="true"
                        [placeHolder]="'Select categories'"></ngx-dropdown-list>

And I am getting all selected values like:

get selectedCategories() {
    const items = this.categoryItems.filter((item: any) => item.selected);
    return items.length ? JSON.stringify(items.map(item => ({
      value: item.value
    }))) : '';

  }

and output looks like:

[{"value":"Surname"},{"value":"Address"}]

I want to get only for example Surname instead of value and Surname.

[0].value

How Can I do this?

Should I use for loop or is better option?

Upvotes: 0

Views: 525

Answers (1)

Kurt Hamilton
Kurt Hamilton

Reputation: 13515

I think you're almost there, in fact you're doing a little too much. Your map function should just return the value you are interested in rather than creating a new structure.

get selectedCategories() {
  const items = this.categoryItems.filter((item: any) => item.selected);
  return items.length ? JSON.stringify(items.map(item => item.value)) : '';
}

Edit:

And as a personal preference, I would refactor to something like this:

get selectedCategories() {
  if (!this.categoryItems.length) {
    return '';
  }

  const surnames = this.categoryItems
    .filter(item => item.selected)
    .map(item => item.value);
  return JSON.stringify(surnames);
}

I prefer to get out of a function early in the case where no further processing is required. And I would return the result of chained filter and map functions into a new surnames variable. The named variable signals the intention of the code, and keeps the array logic together.

This is just my preference though. Your code was almost there functionally.

Upvotes: 2

Related Questions