在node JS中迭代和分割对象文字表示法



我是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。

  1. 将键名从名称替换为列
  2. 当操作符"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我尝试了多种方法来实现改变,但都失败了。请帮助

这应该能奏效:

  1. 检查对象的name属性;如果存在,将其复制到column属性并删除obj.name
  2. 检查obj.operator === 'RANGE';如果true
    1. operator重命名为AND
    2. 创建并添加两个新的单操作对象到args
    3. 删除columntype字段

示例

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));

最新更新