如果数组没有值,我想从数组中删除对象
我有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的对象,我如何才能做到这一点呢?
发布于 2019-09-09 20:49:49
如果希望结果数组只包含包含属性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);
发布于 2019-09-09 21:11:00
正如你所说:
迈克尔不存在于我的数据库中
你设定的条件是
if (res.name === tempList.name.value) {
tempList.userId = res.id; // creating a key and setting value
return tempList;
}
return tempList;由于您的数据库没有'Michael‘值,上述条件是假的。因此,它从if子句中取出,只返回没有userId的内容。
现在,如果您想将'Michael‘userId设置为空。
if (res.name === tempList.name.value) {
tempList.userId = res.id; // creating a key and setting value
} else {
tempList.userId = null;
}
return tempList;然后过滤掉数据使用的类似@。
console.log(data.filter(val => val['userId'] !== null);https://stackoverflow.com/questions/57860546
复制相似问题