To avoid any explicit iteration, you can use Object.keys
with map
to transform each key into the corresponding entry, then simply join
them together:
function fancyString(obj) {
return Object.keys(obj).map(function (k) {
return "" + k + "(" + obj[k] + ")";
}).join("||");
}
var foo = {name: "username", age: 20};
console.log(fancyString(foo));
To offer some explanation of how this work:
The call to Object.keys()
returns an array of the object's own enumerable keys, effectively combining the for (f in o)
and o.hasOwnProperty()
checks. Object.keys
is relatively well-supported, by everything except IE9 (although polyfills are not complicated).
That array of keys are transformed via Array.prototype.map()
, using the desired string formatting. This is pretty simple, but do not that obj[k]
will call its .toString()
method (if available) to transform it into a string. This allows excellent handling of custom objects, as you can simply define a toString
method on each and it will be picked up by the VM. Again, this is supported by IE9 and better, but polyfills are trivial.
Finally, we join the resulting strings with Array.prototype.join()
, which takes care of making sure we don't append the separator to the end or anything like that. All browsers support this.
For curiosity, the ES6 equivalent would be:
let fancyString = o => Object.keys(o).map(k => "" + k + "(" + o[k] + ")").join("||");