简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM