javascript - 更新 for 循环中的嵌套对象
问题描述
我有以下问题我有一组这样的 JSON 规则
{
"event": {
"type": "maxrulecount",
"params": {
"maxrulecount": 2
}
},
"conditions": {
"any": [
{
"all": [
{
"fact": "apples",
"value": "20",
"operator": "greaterThanInclusive"
}
]
},
{
"all": [
{
"fact": "bananas",
"value": "100",
"operator": "greaterThanInclusive"
}
]
}
]
}
}
所以我显然将它转换为一个对象,但数字值仍然是一个字符串,所以我创建了一个函数,它将任何字符串数字转换为数字,如下所示
checkForNumberValues(rules) {
// allows any number of numbers together or a decimal number
let numberRegex = /^(([0-9]{1,})|([0-9]{1,}\.[0-9]{1,}))$/g;
// yes a loop within a loop but time complexity is no issue here
rules?.conditions?.any?.forEach((condition) => {
condition?.all?.forEach((rule) => {
console.log(rule.value, numberRegex.test(rule.value)); // this is working correctly
if (numberRegex.test(rule.value)) {
rule.value = Number(rule.value);
}
});
});
console.log(rules);
return rules;
}
现在我可以看到它正在正确识别数字并设置值但是当我像这样控制台结果时
console.log(checkForNumberValues(rules));
我用字符串数字值而不是我设置的数字值返回规则对象。
我需要做一些特别的事情来设置嵌套值吗?
下面是一个例子
let rules = {
conditions: {
any: [
{
all: [
{ fact: 'orange', value: '70' },
{ fact: 'apple', value: '10' },
{ fact: 'brocolli', value: '54' },
{ fact: 'kiwi fruit', value: '199' }
]
}
]
}
}
function checkForNumberValues(rules) {
let numberRegex = /^(([0-9]{1,})|([0-9]{1,}\.[0-9]{1,}))$/g;
rules.conditions.any.forEach((condition) => {
condition.all.forEach((rule) => {
if (numberRegex.test(rule.value)) {
rule.value = Number(rule.value);
}
})
});
return rules;
}
console.log(checkForNumberValues(rules));
任何帮助,将不胜感激!
解决方案
Regexp
“记住”使用全局标志时找到匹配项的最后一个索引g
(->为什么带有全局标志的 RegExp 会给出错误的结果?)
使用parseInt()
/Number()
然后测试NaN
let rules = {
conditions: {
any: [
{
all: [
{ fact: 'orange', value: '70' },
{ fact: 'apple', value: '10' }
]
}
]
}
}
function checkForNumberValues(rules) {
rules.conditions.any.forEach((condition) => {
condition.all.forEach((rule) => {
const val = parseInt(rule.value);
if (!isNaN(val)) {
rule.value = val;
}
})
});
return rules;
}
console.log(checkForNumberValues(rules));
推荐阅读
- file - 通过 FOR - DO 结构解析不同文件时,CMD 控制台自动关闭
- android - 模糊文本使退格键一次删除两个字符
- python - 项目序列化程序不起作用。函数永远不会被调用
- javascript - 这个 node.js 项目中我的 localhost:5000/users url 有什么问题?
- javascript - 无法弄清楚这个控制溢出测试的答案
- node.js - http:切换源流(mp4视频)
- flutter - 当我运行我的应用程序“验证您的互联网连接 Flutter”
- r - 如何删除列表中每个元素的第一行
- scikit-learn - 什么决策树算法用于 scikit-learn 中的随机森林分类器
- swift - Swift 中的异步线程 - 如何处理?