我有一个多选复选框,如下所示。在此方法getMultiSelectedItems()
上检索所选项目,如下所示。我们说我选择了一个项目。
checked:true,
display: "Co-sleep with parent(s)",
encode : "1",
label : "uiCoSleepNight"
您能告诉我如何在上面的对象中包含所选项目的index
吗?我们可以将index
视为inputs
数组的顺序。
注意:实际上,我需要所选项目的index
。希望有一种方法可以修改getMultiSelectedItems()
来获取它。换句话说,用户已选择的index
array
。
html的
<ion-list>
<ion-item *ngFor="let i of inputs">
<ion-label>{{i.display}}</ion-label>
<ion-checkbox name="{{i.label}}" [(ngModel)]="i.checked"></ion-checkbox>
</ion-item>
</ion-list>
.TS
//get Multi Selected Items
getMultiSelectedItems(): any {
return this.inputs.filter(opt => opt.checked);
}
this.inputs= [
{
"encode": "1",
"display": "Own bed/crib in own room",
"label": "uiOwnRoomOwnBedNight",
"checked": false
},
{
"encode": "1",
"display": "Own bed/crib but share room with sibling(s)",
"label": "uiSharedRoomOwnBedNight",
"checked": false
},
{
"encode": "1",
"display": "Own bed/crib but share room with parent(s)",
"label": "uiParentRoomOwnBedNight",
"checked": false
},
{
"encode": "1",
"display": "Co-sleep with parent(s)",
"label": "uiCoSleepNight",
"checked": false
},
],
答案 0 :(得分:1)
您可以在过滤器中获得的第二个值是index。
return this.inputs.filter((opt, i) => {
if(opt.checked) {opt.index = i; return true;}
});
答案 1 :(得分:0)
希望我能得到你的意见。您可以使用Array.map
生成新的array
,其Array.filter
的结果包含原始数据及其原始数组中的索引。
function getMultiSelectedItems() {
var arr = [];
return this.inputs.filter(opt => opt.checked)
.map(item => {return {"index": inputs.indexOf(item), "data": item};});
}
var inputs = [{
"encode": "1",
"display": "Own bed/crib in own room",
"label": "uiOwnRoomOwnBedNight",
"checked": false
},
{
"encode": "1",
"display": "Own bed/crib but share room with sibling(s)",
"label": "uiSharedRoomOwnBedNight",
"checked": true
},
{
"encode": "1",
"display": "Own bed/crib but share room with parent(s)",
"label": "uiParentRoomOwnBedNight",
"checked": false
},
{
"encode": "1",
"display": "Co-sleep with parent(s)",
"label": "uiCoSleepNight",
"checked": true
},
];
console.log(getMultiSelectedItems());
或者只是您可以将Array.indexOf
与Array.filter
的结果一起使用,但请记住,如果更改了对象的实例(Array.filter的元素),这将不起作用。 / p>
function getMultiSelectedItems() {
return this.inputs.filter(opt => opt.checked);
}
var inputs = [{
"encode": "1",
"display": "Own bed/crib in own room",
"label": "uiOwnRoomOwnBedNight",
"checked": false
},
{
"encode": "1",
"display": "Own bed/crib but share room with sibling(s)",
"label": "uiSharedRoomOwnBedNight",
"checked": true
},
{
"encode": "1",
"display": "Own bed/crib but share room with parent(s)",
"label": "uiParentRoomOwnBedNight",
"checked": false
},
{
"encode": "1",
"display": "Co-sleep with parent(s)",
"label": "uiCoSleepNight",
"checked": true
},
];
getMultiSelectedItems().forEach(item => console.log(inputs.indexOf(item)));