简体   繁体   中英

Join object values into a string with dynamic key names

In an Angular app, I have an HTTP response from the server as a JSON object with some errors. I want to join them all into a string and show them as a message to the user.

At the moment, I have done this:

if ( "errors" in emsg.error ) {
   let msg = emsg.error.map(o => o.name).join(', ');
}

However, I need to write it for every different case of return with different key names. An example of my response is this one:

{  
   "error":{  
      "message":"422 Unprocessable Entity",
      "errors":{  
         "id":[  
            "The id has already been taken."
         ],
         "name":[  
            "The name has already been taken."
         ]
      },
      "status_code":422
   }
}

So, my response can have dynamic object names and each of them may have more than one error. Is there any way to transform the above to a generic code that will handle all the responses of the same format?

 var emsg = { "error":{ "message":"422 Unprocessable Entity", "errors":{ "id":[ "The id has already been taken." ], "name":[ "The name has already been taken." ] }, "status_code":422 } }, array = []; // push all error values into array for (var key in emsg.error.errors) { Array.prototype.push.apply(array, emsg.error.errors[key]); } console.log(array.join(', ')); 

If you can use lodash , you can use flatMap to do it more elegantly,

_.flatMap(emsg.error.errors).join(', ');

get the object keys and iterate the keys array. If the keys exist then join the values

 var emsg = { "error":{ "message":"422 Unprocessable Entity", "errors":{ "id":[ "The id has already been taken." ], "name":[ "The name has already been taken." ] }, "status_code":422 } } var keys = Object.keys(emsg.error.errors); let msg = keys.map(o =>emsg.error.errors[o] ).join(', '); console.log(msg) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM