radosch radosch - 3 months ago 6
Javascript Question

ES6 How to convert key, value pair to string recursively in javascript?

I try to interpolate error messages, because I need it in a special text format.
Whats the best practice doing that nowadays :)
thanks for any help!

http://codepen.io/radosch/pen/wWYPYG?editors=1111

desired outcome:

Password longer then 5 chars \n
Email has invalid format \n


Source:

let data = {
"errors": [
{
"password": "must min have 5 characters"
},
{
"email": "has invalid format"
}
]
}


possible solution:

let res = data.errors.map(function(error, index) {
let keyName = Object.keys(error)
let str = error[keyName]
return keyName + " " + str ;
});

console.log(res.join("\n"));

Answer

Something like this?

data.errors.map(error => Object.keys(error).map(key => `${key} ${error[key]}`)).join('\n');
Comments