按属性值过滤对象属性

时间:2020-08-01 19:52:24

标签: javascript

例如我有一个带有验证规则的对象

validationRules = {
    planType: {
        group: 'personalData',
        required: true,
        messages: {
            required: 'Required Field'
        }
    },
    name: {
        group: 'personalData',
        required: true,
        pattern: /\w+\s+\w+/,
        messages: {
            required: 'Required Field',
            pattern: 'Insert first and last names'
        }
    },
}

我需要逐步验证表单向导,因此我需要创建一个函数来验证每个步骤

function isStepValid() {

    console.log(lastActiveNav);
    const currentStep = lastActiveNav.getAttribute('data-pane');
    var stepRules = validationRules.filter(currentStep); // wont work cause not an array
    console.log(stepRules); // this is the value in the group property in the validationRules



    for (let key in validationRules) {    

        
    }
}

我只想遍历具有匹配的group属性值的属性。可悲的是,我只能使用带有过滤器的阵列来找到答案。

1 个答案:

答案 0 :(得分:1)

const currentStep = lastActiveNav.getAttribute('data-pane');

Object.keys(validationRules)
  .map(key => validationRules[key])
  .filter(validationRule => validationRule.group === currentStep)
  .forEach(validationRule => {  // forEach/map/reduce depending what you want to do
    // Code here
  })