将多维对象数组转换为普通数组

时间:2015-04-26 14:35:05

标签: angularjs

您好我知道如何从laravel验证中获取错误,但现在我的问题是显示它们。我想要一种循环遍历每条错误消息并使用ng-repeat在用户页面上显示的简单方法。

这是我的代码示例:

var req = {
    method: 'POST',
    url: '/customer',
    headers: {
        'X-XSRF-Token': $("meta[name='csrf_token']").attr("content")
    },
    data: {
        fullname: $scope.customer.input.fullname,
        address: $scope.customer.input.address,
        telephone: $scope.customer.input.telephone,
        email: $scope.customer.input.email,
        city: $scope.customer.input.city
    }
}

$http(req)
    .success(function (data, status, headers, config) {
        if (data.url !== undefined)
        {
            window.location.href = data.url;
        }
    })
    .error(function (data, status, headers, config) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
        //alert(data);
    });

返回对象的示例:

{"email":["The email has already been taken.","Email field is required"],"password":["The password must be at least 8 characters
."]}

如何在这样的对象中循环并在用户页面上垂直显示每条消息。我使用bootstrap css框架。

1 个答案:

答案 0 :(得分:1)

将不同的消息放入数组中并根据需要显示它们:

var obj = {"email":["The email has already been taken.","Email field is required"],"password":["The password must be at least 8 characters."]};

var distinctMsgs = [];

for(var prop in obj)
{
   if(obj.hasOwnProperty(prop))
   {
        obj[prop].forEach(function(msg){
            if(distinctMsgs.indexOf(msg) == -1)
            {
                  distinctMsgs.push(msg);
            }
        });
   }
}

console.log(distinctMsgs);

JSFIDDLE