单击按钮时,从对象数组中删除条目

时间:2019-11-20 06:09:20

标签: javascript arrays object

我得到了以下对象,我需要删除一个destination_field,然后在HTML内循环该新对象

var columnDropdownStatesJobDetails = {header: "Collection Status", field: "collection_status"}
          {header: "Hostname", field: "hostName"}
          {header: "Device Id", field: "deviceId"}
          {header: "Sensor data", field: "sensorData"}
          {header: "Destination", field: "destination_id"}
          {header: "Last Reported Time", field: "lastReportedTime"}

以下是我所做的

private setDestColChecked(tabSelected, oldVal, newVal) {
  debugger;
  this.newObj= this.columnDropdownStatesJobDetails;
  if (this.columnDropdownStatesJobDetails.length > 0) {
    this.newObj.filter(function(e) {
      if (tabSelected === 'destinationTab' && (e.field === 'destination_id') && (e.visible === oldVal)) {
        e.visible = newVal;
      } else { 
        // here is my attempt to delete this field
        if (e.field === 'destination_id') {
          delete e.field;
          // return e.field !== 'destination_id';
          // delete this.columnDropdownStatesJobDetails.destination_id;
        } 
      }
    });
    console.log(this.newObj);
  }
}

我在这里做什么错了?

<ng-container *ngFor='let col of columnDropdownStates'>
                        <label *ngIf='col' class="checkbox">
                            <input type="checkbox" id={{col.field}} [checked]="col.visible" name={{col.header}}
                                   (change)="onColumnCheckboxChange($event)"/>
                            <span class="checkbox__input"></span>
                            <span class="checkbox__label">{{col.header}}</span>
                        </label>
                    </ng-container>

2 个答案:

答案 0 :(得分:0)

对您要执行的操作感到有些困惑,但是让我尝试一下。 您正在此处进行过滤。因此,您只需要编写过滤条件,该项目就不会出现在您的输出列表中:

var x = [1, 2, 3, 4]
var y = x.filter(function(e){e > 3})
console.log(y) // y = [4]

但是,如果您想通过迭代foreach进行更改,则应该可以。尚不清楚columnDropdownStatesJobDetails的类型,如果它是地图,则可以delete columnDropdownStatesJobDetails['destination_id']

答案 1 :(得分:0)

尝试一下,只需将其更改为forEach

this.newObj.forEach(function(e) {
        if (tabSelected === 'destinationTab' && (e.field === 'destination_id') && (e.visible === oldVal)) {
            e.visible = newVal;
        } else { 
            if (e.field === 'destination_id') {
               delete e.field;
            } 
        }

    });
    console.log(this.newObj)