Angular2 - 如何将 Rails json 错误响应解构为字符串
Angular2 - how to destructure a Rails json error response into a string
来自 Rails API 的错误响应给了我这个 json 正文:
{"mobile":["is already taken"],"email":["is already taken"]}
如您所见,每个字段都可以有一组与之关联的错误消息。
我正在尝试 'deconstruct' 将它变成一个简单的字符串:
"mobile is already taken, email is already taken"
我正在尝试使用地图并为其提供一个函数。显然我需要考虑这些数组中可能有多个元素的事实,例如:
{"mobile":["is already taken","must start 07 for UK"],"email":["is already taken"]}
然后应该变成:
"mobile is already taken, mobile must start 07 for UK, email is already taken"
可以这样做:
let a = JSON.parse('{"mobile":["is already taken","must start 07 for UK"],"email":["is already taken"]}');
let message = Object.keys(a).reduce((prev, next) => prev.concat(a[next].map(v => next + ' ' + v).join(', ')), []).join(', ');
手头没有任何实际的努力,或者至少没有提供代码,感觉就像在做别人的功课。另一方面,这些是我喜欢的有趣的东西。不需要地图或其他任何东西。只是普通的 TypeScript:
let errorMessages: string[] = [];
let json: string = {"mobile":["is already taken","must start 07 for UK"],"email":["is already taken"]};
let keys: string[] = Object.keys(json);
for(let key of keys) {
for(let msg of json[key]) {
errorMessages.push(key + ' ' + msg);
}
}
console.log(errorMessages.join(', '));
来自 Rails API 的错误响应给了我这个 json 正文:
{"mobile":["is already taken"],"email":["is already taken"]}
如您所见,每个字段都可以有一组与之关联的错误消息。
我正在尝试 'deconstruct' 将它变成一个简单的字符串:
"mobile is already taken, email is already taken"
我正在尝试使用地图并为其提供一个函数。显然我需要考虑这些数组中可能有多个元素的事实,例如:
{"mobile":["is already taken","must start 07 for UK"],"email":["is already taken"]}
然后应该变成:
"mobile is already taken, mobile must start 07 for UK, email is already taken"
可以这样做:
let a = JSON.parse('{"mobile":["is already taken","must start 07 for UK"],"email":["is already taken"]}');
let message = Object.keys(a).reduce((prev, next) => prev.concat(a[next].map(v => next + ' ' + v).join(', ')), []).join(', ');
手头没有任何实际的努力,或者至少没有提供代码,感觉就像在做别人的功课。另一方面,这些是我喜欢的有趣的东西。不需要地图或其他任何东西。只是普通的 TypeScript:
let errorMessages: string[] = [];
let json: string = {"mobile":["is already taken","must start 07 for UK"],"email":["is already taken"]};
let keys: string[] = Object.keys(json);
for(let key of keys) {
for(let msg of json[key]) {
errorMessages.push(key + ' ' + msg);
}
}
console.log(errorMessages.join(', '));