How should I deal with an object who looks like th

2019-02-25 08:22发布

I need to display the error in a form.

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

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.

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

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)

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)

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."]
        }
    }
});

1条回答
做自己的国王
2楼-- · 2019-02-25 08:46

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");
查看更多
登录 后发表回答