用密钥替换json值

时间:2019-10-24 08:32:03

标签: javascript json reactjs

我有一个json列表,其中需要使用下面的正则表达式更改 columnDataType 键。例如,在补给对象中进行的正则表达式测试后,字符变为选择

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" }
];

1 个答案:

答案 0 :(得分:0)

只需遍历键并找到所需的内容:

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
      }
    }
  }
}