我有一个看起来像这样的对象:
const inputObject = {
"startDate": {
"$gte": "2017-03-29T00:00:00.000Z",
"$lte": "2017-08-20T00:00:00.000Z"
},
"$and": [
{ "$or": [
{"details.thing": { "$in": [ "01" ] } },
{"details.thing": { "$in": [ "01" ] } },
{"details.thing": { "$in" : [ "01" ] } },
{"details.thing": { "$in" : [ "01" ] } }
]
},
{
"$or": []
},
{
"$or": []
}
]
}
我需要开发一个函数来删除任何存在的空 { "$or": [] },
子数组。我的预期输出是:
const outputObject = {
"startDate": {
"$gte": "2017-03-29T00:00:00.000Z",
"$lte": "2017-08-20T00:00:00.000Z"
},
"$and": [
{ "$or": [
{"details.thing": { "$in": [ "01" ] } },
{"details.thing": { "$in": [ "01" ] } },
{"details.thing": { "$in" : [ "01" ] } },
{"details.thing": { "$in" : [ "01" ] } }
]
}
]
}
我可以对对象中的第一级数组执行此操作,但我不确定如何对第二级数组执行此操作。
最佳答案
使用Array.prototype.filter
:
const outputObject = {
"startDate": {
"$gte": "2017-03-29T00:00:00.000Z",
"$lte": "2017-08-20T00:00:00.000Z"
},
"$and": [
{
"$or": [
{"details.thing": { "$in": [ "01" ] } },
{"details.thing": { "$in": [ "01" ] } },
{"details.thing": { "$in" : [ "01" ] } },
{"details.thing": { "$in" : [ "01" ] } }
]
},
{
"$or": []
}
]
};
var filtered = outputObject.$and = outputObject.$and
.filter(cond => cond.$or.length > 0)
;
// console.log('filtered', filtered);
// shows only the resulting array, your Object remains
// outputObject
console.log('outputObject', outputObject);
关于javascript - 如果 JavaScript ES6 中为空,则从对象中删除子数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45944264/