Reputation: 4427
Node 12
I have the following JSON string (used as filters for database searches)
{"$and":[{"txnType":{"$in":["Cash Expense"]}}]}
I want that ugly string to look like this so I can display it to the front end:
txnType="Cash Expense"
Here is my method:
function prettyupFilters(uglyFilters){
let filters
filters = uglyFilters
.replace(/{/g,'').replace(/}/g,'')
.replace('$$and','').replace('$$in', '=')
.replace(/[/g,'').replace(/]/g,'')
.replace(/:/g,'').replace(/:/g,'')
return filters
}
But, this produces:
"$nd"["txnTy""$in"["Csh Exns"]]
How do i tweak my code to replace characters in my string to achieve my desired output? Thanks
Upvotes: 0
Views: 54
Reputation: 3106
You can use object destructuring to cover all your basis, and grow the program to handle other cases of different tags rather than making it static to the indexes you currently have
const jsonStr = '{"$and":[{"txnType":{"$in":["Cash Expense"]}}]}';
const jsonObj = JSON.parse(jsonStr);
const { $and: andArr = [] } = jsonObj;
let cleanStr = ""
if(andArr.length) {
const [{ txnType = {} }] = andArr;
const { $in: inArr = [] } = txnType;
if(inArr.length) {
[cleanStr] = inArr;
}
}
console.log(cleanStr);
Upvotes: 0
Reputation: 1110
You should parse the string to an object like this:
JSON.parse("...")
You can then extract the values you need
const obj = JSON.parse(`{"$and":[{"txnType":{"$in":["Cash Expense"]}}]}`)
console.log(`txnType="${obj.$and[0].txnType.$in[0]}"`)
Upvotes: 5