ค้นหาเว็บไซต์

typescript - Angular 6 ค้นหาและลบวัตถุ


จะลบวัตถุในรายการของวัตถุโดยใช้หมายเลขไอดีได้อย่างไร? โดยใช้ Angular 6 เขียนโดยใช้ TypeScript

EntityService.ts

import { Injectable } from '@angular/core';
import { Entity } from '../../models/entity';

@Injectable({
  providedIn: 'root'
})
export class EntityService {

  entities: Entity[] = [
    {
      id: 1, 
      name: 'Entity 1'
    },
    {
      id: 2, 
      name: 'Entity 2'
    },
    {
      id: 3, 
      name: 'Entity 3'
    }
  ];

  constructor() { }

  deleteEntity(id: number) {
    // ???
  }

}

คำตอบ #1

คุณสามารถใช้ filter เพื่อเก็บรายการทั้งหมดยกเว้นรายการที่คุณต้องการลบ:

deleteEntity(id: number) {
  this.entities = this.entities.filter(entity => entity.id !== id);
}

คำตอบ #2

เนื่องจากคุณต้องการค้นหาและลบ มีวิธีใหม่ในการทำสิ่งนี้ใน ES6/2015 โดยใช้ findIndex และตัวกระจายอาร์เรย์:

deleteEntity(id: number) {
    const index = Entities.findIndex(obj => obj.id === id);
    const newData = [
        ...Entities.slice(0, index)
    ];
}

ข้อได้เปรียบเหนือคำตอบข้างต้น:

findIndex อาจจะไม่วนซ้ำทั่วทั้งรายการ

let Entities = [
    {
      id: 1, 
      name: 'Entity 1'
    },
    {
      id: 2, 
      name: 'Entity 2'
    },
    {
      id: 3, 
      name: 'Entity 3'
    }
  ];

let entityId = 3;
const index = Entities.findIndex(obj => obj.id === entityId);
const newData = [
    ...Entities.slice(0, index)
];

console.log(newData);