我是Javascript新手。我有以下Json数据。输入
let data = {
"filters": {
"operator": "AND",
"args": [
{
"operator": "OR",
"args": [
{
"operator": "EQ",
"name": "consumer_id",
"args": [
"200"
],
"type": "string"
},
{
"operator": "AND",
"args": [
{
"operator": "RANGE",
"name": "created_date",
"args": [
{"from":1},{"to":2}
],
"type": "number"
},
{
"operator": "EQ",
"name": "state",
"args": [
"TN"
],
"type": "string"
}
]
}
]
},
{
"operator": "GE",
"name": "Character",
"args": [
"H"
],
"type": "string"
}
]
}
我正在尝试用以下更改创建一个新的Json。
- 将键名从名称替换为列
- 当操作符"range";,使用LE和GE将其分成2个操作符。
预期输出
{
"filters": {
"operator": "AND",
"args": [
{
"operator": "OR",
"args": [
{
"operator": "EQ",
"column": "consumer_id",
"args": [
"200"
],
"type": "string"
},
{
"operator": "AND",
"args": [
{
"operator": "LE",
"column": "created_date",
"args": [
1
],
"type": "number"
},
{
"operator": "GE",
"column": "created_date",
"args": [
2
],
"type": "number"
},
{
"operator": "EQ",
"column": "state",
"args": [
"TN"
],
"type": "string"
}
]
}
]
},
{
"operator": "GE",
"column": "character",
"args": [
"H"
],
"type": "string"
}
]
}
}
我的代码:
data.filters.args.filter( item => {
iterateObject(item);
});
function iterateObject(obj) {
for(var prop in obj) {
if(typeof(obj[prop]) === "object" ) {
iterateObject(obj[prop]);
} else {
if (prop === "operator" && obj[prop] === "RANGE") {
obj={
"LE": {"operator": "LE",
"column": obj.name,
"args": [obj.args[0].from],
"type": obj.type
},
"GE":{
"operator": "GE",
"column": obj.name,
"args": [obj.args[1].to],
"type": obj.type
}
}
console.log(obj) // The object gets replaced here, but I don't know how to map with original Json( ie, to the variable data )
}
if (prop === "name" ) {
prop="column"
}
}
}
}
console.log(JSON.stringify(data));
问题:
我能够成功地实现改变1我尝试了多种方法来实现改变,但都失败了。请帮助
这应该能奏效:
- 检查对象的
name
属性;如果存在,将其复制到column
属性并删除obj.name
- 检查
obj.operator === 'RANGE'
;如果true
,- 将
operator
重命名为AND
- 创建并添加两个新的单操作对象到
args
删除
column
和type
字段 - 将
示例
let data = {
"filters": {
"operator": "AND",
"args": [
{
"operator": "OR",
"args": [
{
"operator": "EQ",
"name": "consumer_id",
"args": [
"200"
],
"type": "string"
},
{
"operator": "AND",
"args": [
{
"operator": "RANGE",
"name": "created_date",
"args": [
{"from":1},{"to":2}
],
"type": "number"
},
{
"operator": "EQ",
"name": "state",
"args": [
"TN"
],
"type": "string"
}
]
}
]
},
{
"operator": "GE",
"name": "Character",
"args": [
"H"
],
"type": "string"
}
]
}
};
function modify(obj) {
if (!obj) return;
if (obj.name) {
obj.column = obj.name
delete obj.name;
}
if (obj.operator === 'RANGE') {
obj.operator = 'AND';
obj.args = [
{
"operator": "GE",
"column": obj.column,
"args": [ obj.args[0].from ],
"type": obj.type
},
{
"operator": "LE",
"column": obj.column,
"args": [ obj.args[1].to ],
"type": obj.type
}
];
delete obj.column;
delete obj.type;
}
for (const arg of obj.args || []) {
modify(arg);
}
}
modify(data.filters);
console.log(JSON.stringify(data, null, 2));