【发布时间】:2022-11-26 19:31:36
【问题描述】:
我有一个字符串,
const string = "DEVICE_SIZE IN ('036','048','060','070') AND DEVICE_VOLTAGE IN ('1','3') AND NOT DEVICE_DISCHARGE_AIR IN ('S') AND NOT DEVICE_REFRIGERANT_CIRCUIT IN ('H','C')";
由此,我需要映射相应的键和值,如 DEVICE_SIZE: ["036", "048", "060", "070"]
当前结果:
const string =
"DEVICE_SIZE IN ('036','048','060','070') AND DEVICE_VOLTAGE IN ('1','3') AND NOT DEVICE_DISCHARGE_AIR IN ('S') AND NOT DEVICE_REFRIGERANT_CIRCUIT IN ('H','C')";
const res = string.split('IN ');
const regExp = /\(([^)]+)\)/;
const Y = 'AND';
const data = res.map((item) => {
if (regExp.exec(item)) {
return {
[item.slice(item.indexOf(Y) + Y.length)]: regExp.exec(item)[1],
};
}
});
console.log('data ', data);
预期结果:
[
{ "DEVICE_SIZE": ["036", "048", "060", "070"] },
{ "DEVICE_VOLTAGE": ["1", "3"] },
{ "NOT DEVICE_DISCHARGE_AIR": ["s"] },
{ "NOT DEVICE_REFRIGERANT_CIRCUIT": ["H", "C"] },
];
根据我对当前结果的尝试,我无法得到确切的结果。您能帮我实现上述预期结果吗?
笔记:我正在尝试以上方法来实现我上一个问题中提到的最终结果 How to get valid object from the string matching respective array?
【问题讨论】:
-
像这样解析字符串很容易出错并且很可能会中断,为什么你需要这样做?
标签: javascript arrays string