Javascript从数组中删除对象而不删除所选对象

问题描述 投票:-1回答:6

我正在使用Angular 5,我创建了一个从数组中删除对象的函数:

这是数据:

this.widgets = [
   { id: 1, title: 'Object 1', config: { row: 1, col: 1, sizex: 1 }}
   { id: 2, title: 'Object 2', config: { row: 1, col: 2, sizex: 1 }}
];

这是功能:

removeObj(id) {
  this.widgets.splice( this.widgets.indexOf(id), 1 );
}

这在我的组件的html部分:

<div *ngFor="let widget of widgets" [(ngWidget)]="widget.config">
    <button (click)="removeObj(widget.id)">X</button>
    <div class="title">{{widget.title}}</div>
    <p>{{widget.id}}</p>
</div>

我需要它只是删除所选对象,但它只是删除第一个对象。

我怎样才能解决这个问题?

javascript angular
6个回答
2
投票

尝试使用array.prototype.filter:

this.widgets = [
    { id: 1, title: 'Object 1', config: { row: 1, col: 1, sizex: 1 }}
    { id: 2, title: 'Object 2', config: { row: 1, col: 2, sizex: 1 }}
];

removeObj(id) {
    this.widgets = this.widgets.filter(widget => widget.id !== id);
}

2
投票

removeObj函数中,您必须搜索参数中传递的id。你不能只使用indexOf来获取索引。

removeObj(id) {
   var index = -1;
   this.widgets.forEach((widget, i) => {
        if(widget.id === id) {
            index= i;
            return;
        }
   });
   this.widgets.splice( this.widgets.indexOf(index), 1 );
}

0
投票

您还可以尝试以下一行代码

delete this.widgets[this.widget.indexOf(id)];

0
投票

ID是您的对象属性,而不是数组索引。你可以这样做:

<div *ngFor="let widget of widgets; let i = index" [(ngWidget)]="widget.config">
    <button (click)="removeObj(i)">X</button>
    <div class="title">{{widget.title}}</div>
    <p>{{widget.id}}</p>
</div>

0
投票

尝试在拼接前映射数组:

removeObj(id) {
   widgets.splice((widgets.map(o => o.id)).indexOf(id) , 1);
}

0
投票

试试这个

  removeObj(id) {
  let index = this.widgets.findIndex(function (o) {
            return o.id === id;
        })
  this.widgets.splice(index, 1);
  }
© www.soinside.com 2019 - 2024. All rights reserved.