如何从数组中删除对象

How to delete objects from array

如果对象没有值,我想从数组中删除它们

我有 API A,对我来说 return 这个 JSON:

{
  "code": 0,
  "data": [
    {
      "name": {
        "value": "Ana"
      },
      "fruit": {
        "value": "Grape"
      },
      "from": {
        "value": "BR"
      }
    },
    {
      "name": {
        "value": "Michael"
      },
      "fruit": {
        "value": "Apple"
      },
      "from": {
        "value": "US"
      }
    }
  ]
}

通过 API B,我可以 return 这个用户的 id 传递给她名字

我有这个代码:

getData() {
  this.myService.getDataAPI_A()
    .subscribe((res) => {
      this.myList = res['data'];
      if (this.myList) {
        for (const key of this.myList) {
          this.getId(key.name.value);
        }
      }
    });
}

getId(name) {
  this.myService.getDataAPI_B(name) // api B returns id with the name
    .subscribe((res) => {
      this.myList.map((tempList) => {
        if (res.name === tempList.name.value) {
          tempList.userId = res.id; // creating a key and setting value
          return tempList;
        }
        return tempList;
      });
    });
}

然后我得到了这个 json:

{
  "code": 0,
  "custodyBovespa": [
    {
      "name": {
        "value": "Ana"
      },
      "userId": "43",
      "fruit": {
        "value": "Grape"
      },
      "from": {
        "value": "BR"
      }
    },
    {
      "name": {
        "value": "Michael"
      },
      "fruit": {
        "value": "Apple"
      },
      "from": {
        "value": "US"
      }
    }
  ]
}

Michael 在我的数据库中不存在,所以 api return 对我来说是空的, 出于某种原因,不要在我的 json 中创建密钥(为什么?)。 在此之后我想删除没有 userId 的对象 我该怎么做?

如果您希望结果数组只包含包含 属性 userId 的对象,您可以简单地使用普通的 JavaScript .filter.

在下面的示例中,我将删除任何没有 "userId" 属性的元素。

var data = [
  {
    "name": {
      "value": "Ana"
    },
    "userId": "43",
    "fruit": {
      "value": "Grape"
    },
    "from": {
      "value": "BR"
    }
  },
  {
    "name": {
      "value": "Michael"
    },
    "fruit": {
      "value": "Apple"
    },
    "from": {
      "value": "US"
    }
  }
];
var dataFiltered = data.filter(val => val["userId"]);
console.log(dataFiltered);

如你所说:

Michael does not existe in my data base

你设置的条件是

if (res.name === tempList.name.value) {
  tempList.userId = res.id; // creating a key and setting value
  return tempList;
}
return tempList;

由于您的数据库没有值'Michael',以上条件不成立。因此,它脱离了 if 子句,只是 return 没有 userId 的情况。

现在,如果您想将 'Michael' userId 设置为 null。

if (res.name === tempList.name.value) {
  tempList.userId = res.id; // creating a key and setting value
} else {
  tempList.userId = null;
}
return tempList;

然后像@Rich 回答的那样过滤掉数据的使用。

console.log(data.filter(val => val['userId'] !== null);