【发布时间】:2021-10-19 18:33:55
【问题描述】:
我有以下需要转换的数组格式示例。
{ [
{
"condition": "$and",
"children": [
{ "column": "Title", "comparison": "$eq", "columnValue": "1" },
{ "column": "Event Status", "comparison": "$eq", "columnValue": "2" }
]
},
{
"condition": "$or",
"children": [
{
"column": "Issue Description",
"comparison": "$lt",
"columnValue": "3"
},
{ "column": "Number Label", "comparison": "$gte", "columnValue": "4" }
]
}
]}
需要这样改造……
{
[
{
"$and" : [
{
"Title" : {
"$eq" : "1"
}
},
{
"Event Status" : {
"$eq" : "2"
}
}
]
},
{
"$or" : [
{
"Issue Description" : {
"$lt" : "3"
}
},
{
"Number Label" : {
"$gte" : "4"
}
}
]
}
]
}
我已经尝试了 map 和 reduce 的各种迭代。接近了,但不完全在那里。
这是在一个 Vue 项目中。这是我尝试过的一个示例。
const result = this.parents.map(({ condition, children }) => {
const childArray = children.reduce(
(c, v) => ({
...c,
[v.column]: { [v.comparison]: v.columnValue }
}),
{}
);
childArray.condition = condition;
return childArray;
});
这会返回:
[
{
"Title": { "$eq": "1" },
"Event Status": { "$eq": "2" },
"condition": "$and"
},
{
"Issue Description": { "$lt": "3" },
"Number Label": { "$gte": "4" },
"condition": "$or"
}
]
我不知道如何将“条件”键放在正确的位置。
【问题讨论】:
-
如果您尝试了不同的方法,请将它们包含在内,以便人们可以发现您可能出错的地方并更好地帮助您,而不是认为其他人会为我编写代码
-
分两步完成。通过其中的每一个进行映射以提取条件将非常容易。
-
您的 JSON 来源无效 ->
{ [
标签: javascript json mongodb