I'm new to Javascript. I have below Json data. Input
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"
}
]
}
I'm trying to do create a new Json with the following changes.
- Replace the key name from name to column.
- When the operator "RANGE" is found, split it into 2 operators using LE and GE.
Expected Output
{
"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"
}
]
}
}
My code:
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));
Question:
I'm able to successfully achieve the change 1 I tried multiple ways to achieve change 2, I could not. Please help