我正在尝试使用ngx下拉列表,如下所示:
<ngx-dropdown-list [items]="categoryItems" id="categoriesofdata" [multiSelection]="true"
[placeHolder]="'Select categories'"></ngx-dropdown-list>
我得到所有选择的值,例如:
get selectedCategories() {
const items = this.categoryItems.filter((item: any) => item.selected);
return items.length ? JSON.stringify(items.map(item => ({
value: item.value
}))) : '';
}
输出类似:
[{“ value”:“ Surname”},{“ value”:“ Address”}]
我只想获取例如姓氏而不是值和姓氏。
[0].value
我该怎么做?
我应该使用for循环还是更好的选择?
答案 0 :(得分:2)
我认为您快到了,实际上您做得太多了。您的map函数应该只返回您感兴趣的值,而不是创建一个新结构。
get selectedCategories() {
const items = this.categoryItems.filter((item: any) => item.selected);
return items.length ? JSON.stringify(items.map(item => item.value)) : '';
}
编辑:
根据个人喜好,我将重构为以下内容:
get selectedCategories() {
if (!this.categoryItems.length) {
return '';
}
const surnames = this.categoryItems
.filter(item => item.selected)
.map(item => item.value);
return JSON.stringify(surnames);
}
在不需要进一步处理的情况下,我希望尽早退出该功能。然后,我将链接的过滤器和映射函数的结果返回到新的姓氏变量中。命名变量表示代码的意图,并将数组逻辑保持在一起。
这只是我的偏爱。您的代码几乎在功能上都在那里。