首页 > 解决方案 > 更新 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));

任何帮助,将不胜感激!

标签: javascript

解决方案


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));


推荐阅读