首页 > 解决方案 > 从任何 [] 对象集合中删除单个对象

问题描述

我在打字稿中有一个像这样声明的对象

public profileDataSource: { Value: string, Key: number }[];

所以我会有一个看起来像这样的对象

   0: Object {Value: "<Select Profile>", Key: null}
    Key:null
    Value:"<Select Profile>"
   1: Object {Value: "Profile 1", Key: 1}
    Key:1
    Value:"Profile 1"

如何删除包含“选择配置文件”值的对象?

profileDataSource.splice(0,1)给我一个错误,即 splice 不是函数

标签: javascripttypescript

解决方案


在我看来,您使用的是 Angular。主要来自您看起来像是在使用某种下拉菜单的概念。

我想介绍一个解决此类问题的解决方案。

从概念上讲,您要创建一个下拉列表,并且每个下拉列表都有一个基本案例及其选项。基本情况可以是某种字符串,表示选择一个选项或其他内容。您可以使用此基本案例来验证所需状态。

我会做的事情如下。

标记:

<select name="selection" [(value)}="selectionOption">
    <option [value]="base.value">{{base.label}}</option>
    <option *ngFor="let item in listOfOptions"
            [value]="item.value">{{item.label}}</option>
</select>

然后在你的标记中你可以有类似的东西:

class MyController {
    selectionOption: any;
    base : Item = { value: null, label: "<Select A Profile>" };
    listOfOptions: Item[] = [];

    ngOnInit() {
        //this.listOfOptions = ...; ///Whatever you want it to contain.
    }
   // Depending how you handle the data, with an NgModel, or FormGroup, you can validate that information.  If value is null, then no selection was done.  Otherwise, you can move to the next step in the validation pipeline.
}

class Item {
    value: any;
    label: string;
}

推荐阅读