如何从对象数组中删除满足条件的对象?

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

我在函数中收到具有以下信息的对象

{
  "name": "Grand modèle",
  "description": "Par 10",
  "price": 0,
  "functional_id": "grand_modele_par_10",
  "quantity": 2,
  "amount": 0
}

并且我需要检查下一个放置它的对象数组以将其删除

[
  {
    "name": "Matériel crémation",
    "products": [
      {
        "file": "data:image/;base64,",
        "name": "Sacs bordeaux",
        "description": "Pour les crémations Référence",
        "id": 12,
        "path": "",
        "items": [
          {
            "name": "Petit modèle",
            "description": "Par 25",
            "price": 0,
            "functional_id": "petit_modele_par_25",
            "quantity": 2,
            "amount": 0
          },
          {
            "name": "Grand modèle",
            "description": "Par 10",
            "price": 0,
            "functional_id": "grand_modele_par_10",
            "quantity": 2,
            "amount": 0,
            "itemAdded": false
          }
        ]
      }
    ]
  },
  {
    "name": "Documents",
    "products": [
      {
        "file": "data:image/;base64,",
        "name": "Affiches procédure",
        "description": "De prise en charge",
        "id": 18,
        "path": "",
        "items": [
          {
            "price": 0,
            "functional_id": "affiches_procedure",
            "quantity": 1,
            "amount": 0
          }
        ]
      }
    ]
  }
]

为此,我通过带有'forEach'的对象数组来查找满足相等条件的项目并将其删除

public deleteItem(item) {


        this.fullCartInfo.forEach(category => {
            category.products.forEach(product => {
                product.items.forEach(itemAdded => {
                    if (item.functional_id === itemAdded.functional_id) {
                        this.fullCartInfo.splice(itemAdded);
                    }
                });
            });
        });
        this.cartService.removeItem(item);
    }


我得到的是他清空我的对象数组。我怎样才能让他删除仅符合条件的那个人?我怎么了谢谢大家的时间

javascript arrays angular7 splice arrayobject
1个回答
0
投票

[Array.prototype.splice(start[, deleteCount[, item1[, item2[, ...]]]])期望应删除的第一个元素的索引(Array.prototype.splice(start[, deleteCount[, item1[, item2[, ...]]]])),以及可选地应删除的元素数(start)。

对于deleteCount索引,我们可以使用start回调的第二个参数,它是集合中当前元素的索引。

以下示例使用:

  • 一组简化的数据
  • 一个常规函数而不是您的类方法,只是因为它更易于使用。您可以将函数的主体复制并粘贴到Array.prototype.forEach()方法中。

Array.prototype.forEach()
© www.soinside.com 2019 - 2024. All rights reserved.