2017-05-22 55 views
0

我有一個Laravel後端通過Validator返回一些錯誤。這些錯誤通過由角度創建的HTTP響應傳遞,並以JSON格式返回。Javascript字符串/對象/數組與JSON混淆

目的如下所示的結構:

name即對象有一個值,它是實際的消息,我是後。

目前,使用循環等等,我只能得到陣列(name)以字符串形式的名稱...

我有時會收到此錯誤對象中多個陣列,我不會永遠知道他們的名字,那麼我怎麼才能在循環中檢索他們每個中的0-索引值?

感謝您的任何幫助。


編輯#1

通過像這樣循環:

for(var err in res.data.errors){ 
    console.log(Object.err[0][0]); 
} 

給了我一個Cannot get [0] index of undefined

+0

不能你,索引0?像'Object.specificitem [index] [0]'? – Diego

+0

編輯,也不爲我工作,謝謝 –

+1

哦,我missunderstanded,我認爲你只引用一級索引,這可以幫助:'for(var index in Object){Object [index] [0]} ' – Diego

回答

0

如何:

let errors = Object.values(response.data.errors); 
// errors is now an array of arrays containing the validation errors 
errors.forEach((errorArray) => { 
    console.log(errorArray[0]); 
}); 

另一種方法是使用Object.keys()而不是值。這類似於你已經試過了,你在哪裏得到的錯誤屬性作爲字符串的名稱,然後用它來訪問每個錯誤數組:它使用,在循環過程

let keys = Object.keys(response.data.errors); 
keys.forEach((errorKey) => { 
    console.log('error type', errorKey); 
    let errorArray = response.data.errors[errorKey]; 
    console.log(errorArray[0]); 
});