我应该如何处理看起来像这样的物体 [英] How should I deal with an object who looks like this

查看:97
本文介绍了我应该如何处理看起来像这样的物体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在表单中显示错误。

I need to display the error in a form.

如果在子项中定义了错误,则错误可以附加到输入名称表单,这是常见情况(1)。

The error can be appended to the input-name form, in case of error defined in children, which is the common case (1).

但是可能发生错误是在json对象(2)的根节点中定义的。

在这种情况下应该附加到formElement。

But could happen that the error is defined in the root node of the json object (2).
In this case it should be appended to the formElement.

以下代码(3)适用于案例(1)但不适用于案例(2)。

The following code (3) works for the case (1) but not for the case (2).

如何修改它以使其在两种情况下都能正常工作?

PS:我使用下划线和jquery。

How should I modify it in order to make it working in both cases?
P.S.: I am using underscore and jquery.

(1)

var xhrObj_1 = JSON.parse('{ "children":{"points":{"errors":["This value should not be blank."]},"message":[],"recipient_id":{"errors":["This value should not be blank."]}}}');






(2)


(2)

var xhrObj_2 = JSON.parse('{ "errors":["This form should not be …."], "children":{"points":{"errors":["This value should not be blank."]},"message":[],"recipient_id":{"errors":["This value should not be blank."]}}}');






(3)


(3)

var parser = function (object) {
    _.each(object, function (xhrObject, name) {
        console.log(xhrObject)

        if (xhrObject.errors) {
            var inputElement = element.find('[name="' + name + '"]');

            inputElement.closest('.control-group')
                .addClass('error');

            parserError(xhrObject.errors, inputElement);

        } else {
            parser(xhrObject); // it is ok for xhrObj_1
                               // it fails for xhrObj_2
        }
    });
};

// example with xhrObj_2 which does not work
parser({
    "errors": ["errro1"],
    "children": {
        "points": {
            "errors": ["This value should not be blank."]
        },
        "message": [],
        "recipient_id": {
            "errors": ["This value should not be blank."]
        }
    }
});


推荐答案

你应该在顶级开始递归:

You should start the recursion at top level:

var xhr = JSON.parse("…");

(function recurse(obj, name) {
    if (obj.errors) {
        var inputElement = element.find('[name="' + name + '"]');
        inputElement.closest('.control-group').addClass('error');
        parserError(obj.errors, inputElement);
    }
    if ("children" in obj)
        for (var prop in obj.children)
            recurse(obj.children[prop], prop);
})(xhr, "top");

这篇关于我应该如何处理看起来像这样的物体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆