gpt4 book ai didi

javascript - ngx下拉列表获取选定值

转载 作者:行者123 更新时间:2023-12-01 00:08:38 24 4
gpt4 key购买 nike

我正在尝试使用这样的 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 循环还是更好的选择?

最佳答案

我认为你已经快到了,事实上你做得有点太多了。您的映射函数应该只返回您感兴趣的值,而不是创建新的结构。

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);
}

在不需要进一步处理的情况下,我更喜欢尽早退出函数。我会将链接过滤器和映射函数的结果返回到一个新的姓氏变量中。命名变量表示代码的意图,并将数组逻辑保持在一起。

但这只是我的偏好。您的代码在功能上已经差不多了。

关于javascript - ngx下拉列表获取选定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60202788/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com