I have a json list in which I need to change the columnDataType key with the regexp below. For example, the char becomes select after the regexp test given in the replecement object.
const list = [
{
"a": {
"columnName" : "a",
"columnDataType": "char",
"columnType": "categoricalValues",
"categoricalValues": [
"Pre",
"Post"
]
},
"b": {
"columnName" : "b",
"columnDataType": "int",
"columnType": "range",
"categoricalValues": [],
"range": {
"min": "1",
"max": "250"
}
},
"c": {
"columnName" : "c",
"columnDataType": "date",
"columnType": "value",
"categoricalValues": []
},
"d": {
"columnName" : "d",
"columnDataType": "categoricalValues",
"columnType": "value",
"categoricalValues": [
"TRUE",
"FALSE"
]
}
}
];
const replacements = [
{ criteria: /^(char.*\([0-9]{0,5}\)|char|varchar)$/, replacement: "select" },
{ criteria: /^(int|integer|.{1,}int|(numeric\(\d{1,2},\d{1,2}\))|number|decimal)$/, replacement: "range" },
{ criteria: "boolean", replacement: "select" },
{ criteria: /^date.*$/, replacement: "date" },
{ criteria: /^time.*$/, replacement: "date" }
];
Just iterate through keys and find needed:
function replace(list, replacements) {
return replacements.reduce(replaceOne, list);
}
function replaceOne(list, replacement) {
return Object.entries(list).reduce(replaceValue(replacement), list);
}
function replaceValue({ criteria, replacement }) {
return (list, [ key, value ]) => {
if (! criteria.test(value.columnDataType)) {
return list;
}
return {
...list,
[key]: {
...value,
columnDataType: replacement
}
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.