gpt4 book ai didi

javascript - 如果在 Javascript ES6 中为空,则从对象中删除子数组

转载 作者:行者123 更新时间:2023-11-29 19:02:19 25 4
gpt4 key购买 nike

我有一个看起来像这样的对象:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com