如何从数组中删除对象

时间:2019-09-09 20:04:26

标签: arrays json angular array-splice

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

我有API A,可以向我返回此JSON:

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

使用API​​ B,我可以返回该用户的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返回给我null, 出于某种原因不要在我的json中创建密钥(为什么?)。 之后,我要删除没有userId的对象 我该怎么做?

2 个答案:

答案 0 :(得分:3)

如果您希望结果数组仅包含包含属性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);

答案 1 :(得分:0)

如您所说:

  

我的数据库中不存在Michael

您设置的条件是

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

由于您的数据库没有值'Michael',因此上述条件为false。因此,它脱离了if子句,只返回没有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);
相关问题