I have object like this:
{
Name: "John"
Location: "Unknown"
Type: "Unknown"
Status: "Unknown"
Phone_number: "Unknown"
}
Need to format it like this (with tabs or spaces):
Name: John // three tabs
Location: Unknown // two tabs
Type: Unknown // three tabs
Status: Unknown // three tabs
Phone_number: Unknown // one tab
Java and Perl has this functionality in printf, but how to do this in javascript?
Ok. Found here:
/**
* object.padding(number, string)
* Transform the string object to string of the actual width filling by the padding character (by default ' ')
* Negative value of width means left padding, and positive value means right one
*
* @param number Width of string
* @param string Padding chacracter (by default, ' ')
* @return string
* @access public
*/
String.prototype.padding = function(n, c)
{
var val = this.valueOf();
if ( Math.abs(n) <= val.length ) {
return val;
}
var m = Math.max((Math.abs(n) - this.length) || 0, 0);
var pad = Array(m + 1).join(String(c || ' ').charAt(0));
// var pad = String(c || ' ').charAt(0).repeat(Math.abs(n) - this.length);
return (n < 0) ? pad + val : val + pad;
// return (n < 0) ? val + pad : pad + val;
};
This not works with tabs, but works with spaces exactly how I describe in question.
For my example code will be:
$.each(myObj, function(myKey, myVal) {
myOut += myKey.padding(20) + " = " + myVal + "\r\n";
});
Output will be:
Name = John
Location = Unknown
Type = Unknown
Status = Unknown
Phone_number = Unknown