【问题标题】:Javascript recursive object iteration generating form elements namesJavascript递归对象迭代生成表单元素名称
【发布时间】:2018-03-16 18:32:38
【问题描述】:

我有一个 AJAX 响应,其中包含一个对象,该对象存储我的所有表单元素结构及其各自的错误消息(如果有)。 该对象结构的构建如下:

var obj = {
    'entity1': { //Entity
        'attribute1': { //Field
            'isEmpty': "This value is required" //rule with error message
        },
        'attribute2': { //Field
            'isEmpty': "This value is required" //rule with error message
        }
    },
    'entity2': { //Entity
        'attribute1': { //Field
            'isEmpty': "This value is required" //rule with error message
        },
        'attribute2': { //Field
            'isEmpty': "This value is required" //rule with error message
        }
    }
};

所有这些字段都存储在由主实体包围的表单中,如下所示:

<input name="mainentity[entity1][attribute1]" />
<input name="mainentity[entity1][attribute2]" />
<input name="mainentity[entity2][attribute1]" />
<input name="mainentity[entity2][attribute2]" />
...

基本上,我需要迭代这个对象,组装输入的名称,以便能够使用 jQuery 找到它们,这样我就可以将它们各自的错误消息添加到 DOM。

我尝试在 javascript 中创建这个函数:

var prefix = 'mainentity', inputs = {};
function iterate(obj, partialName, isChild) {
    for (var property in obj) {
        if (obj.hasOwnProperty(property)) {
            switch (typeof obj[property]) {
                case 'string':
                    if (!inputs.hasOwnProperty(partialName)) {
                        inputs[partialName] = [];
                    }
                    inputs[partialName].push(obj[property]);
                    break;
                default:
                    if (isChild) {
                        partialName += '[' + property + ']';
                    } else {
                        partialName = prefix + '[' + property + ']';
                    }
                    iterate(obj[property], partialName, true);
                    break;
            }
        }
    }
};
iterate(obj);
console.log(inputs);

我基于属性的类型。如果string,那么这是一条消息。否则它是一个需要在递归中考虑的字段。我尝试使用标志 isChild 只是为了知道我什么时候会破坏 partialName 并作为新属性重新开始。

问题是最终结果变成了这样:

{
    'mainEntity[entity1][attribute1]': ["This value is required"],
    'mainEntity[entity1][attribute1][attribute2]': ["This value is required"], //wrong result, attribute1 shouldn't be here
    'mainEntity[entity2][attribute1]': ["This value is required"],
    'mainEntity[entity2][attribute1][attribute2]': ["This value is required"], //wrong result, attribute1 shouldn't be here
}

我希望这样:

{
    'mainEntity[entity1][attribute1]': ["This value is required"],
    'mainEntity[entity1][attribute2]': ["This value is required"], //No attribute 1 here
    'mainEntity[entity2][attribute1]': ["This value is required"],
    'mainEntity[entity2][attribute2]': ["This value is required"], //No attribute 1 here
}

我理解这个问题。 isChild 标志仅适用于更高级别,并且考虑到在我的逻辑中,从递归开始的所有内容都是子级,partialName 无法正常工作。

我怎样才能使这个功能按我的预期工作?我的意思是,我怎么知道将部分名称分解为新输入的正确时间,而不是连接到错误的先前字段,并使其适用于 N 嵌套响应对象的任何情况?

【问题讨论】:

    标签: javascript forms loops recursion logic


    【解决方案1】:

    这种替代方法递归循环并连接来自对象的每个新找到的键。

    var obj = {  'entity1': {    'attribute1': {       'isEmpty': "This value is required1"     },    'attribute2': {      'isEmpty': "This value is required2"     }  },  'entity2': {  'attribute1': {       'isEmpty': "This value is required3"  },    'attribute2': {     'isEmpty': "This value is required4"   }  }};
    
    function loop(o, currentPath, result) {
      Object.keys(o).forEach(function(k) {
        if (typeof o[k] === 'string') result[`${currentPath}`] = [o[k]];
        else loop(o[k], `${currentPath}[${k}]`, result);    
      });
    }
    
    var result = {};
    loop(obj, 'mainEntity', result);
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    【讨论】:

    • 伟大而简单的解决方案,非常感谢!我只是做了一些小的调整,以适应输入有多个消息的情况!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-04
    • 2011-01-13
    • 2020-04-24
    • 2023-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多